Home > Article > Backend Development > How to Accurately Round Decimals to Two Places with Precision in PHP?
PHP Rounding Decimals to Two Places with Precision
You're looking to reduce a decimal number in PHP to two decimal places. Specifically, you want to convert 49.955 to 49.95. The number_format function rounds the value to 49.96, while substr can't be used if the number is smaller than two decimal places.
The solution involves multiplying the number by 100, taking its floor value, and dividing it back by 100. This can be expressed as follows:
<code class="php">$roundedNumber = floor($number * 100) / 100;</code>
This method accurately rounds the number down to two decimal places, ensuring precision in your calculations.
The above is the detailed content of How to Accurately Round Decimals to Two Places with Precision in PHP?. For more information, please follow other related articles on the PHP Chinese website!