Home >Backend Development >PHP Tutorial >PHP implements keeping two decimal places

PHP implements keeping two decimal places

小云云
小云云Original
2018-03-20 14:36:4029283browse

We often need to retain decimal places when developing PHP. For example, when displaying amounts, we usually need to retain two decimal places. In addition to setting the amount field to decimal (n, 2) when designing the database , decimal places can also be processed through PHP. There are many functions that can process numbers in PHP. Let’s list the commonly used functions for processing numbers:

1.sprintf() function

This function can achieve rounding, and if it does not have decimal places, it will automatically use the specified character (specified 0) to fill in the specified decimal places

echo sprintf("%01.2f", 5.228);	//	5.23
echo sprintf("%01.2f", 5.224);	//	5.22
echo sprintf("%01.2f", 5);		//	5.00

2.number_format( )Function

This function can achieve rounding, and if it does not have decimal places, it will automatically fill it with 0 to the specified decimal places

echo number_format(5.228,2);	//	5.23
echo number_format(5.224,2);	//	5.22
echo number_format(5,2);		//	5.00

3. round() function

This function can achieve rounding, but if it does not have decimal places, it will not have decimal places after processing

echo round(5.228,2);	//	5.23
echo round(5.224,2);	//	5.22
echo round(5,2);		//	5


4 .php Rounding to the nearest whole number

echo ceil(4.4);		//	5
echo ceil(4.6);		//	5


5.php Rounding to the nearest whole number (rounding down)

echo floor(4.4);		//	4
echo floor(4.6);		//	4

Related recommendations:

Three ways to achieve two decimal places in PHP

PHP ways to keep two decimal places and round or not round

php Keep two decimal places

The above is the detailed content of PHP implements keeping two decimal places. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn