PHP implements keeping two decimal places

小云云
Release: 2023-03-21 19:16:02
Original
29185 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login


4 .php Rounding to the nearest whole number

echo ceil(4.4);		//	5
echo ceil(4.6);		//	5
Copy after login


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

echo floor(4.4);		//	4
echo floor(4.6);		//	4
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!