When I see the title, I believe many friends will think of using the rounding method to achieve it. This is also a method, but there are other methods. Let's take you through several ways to retain two decimal places in PHP!
php method to take two decimal places.
Method 1. It is often used to select a few decimal places but cannot carry.
For example, 3.149569 is taken to two decimal places, and the last two digits cannot be rounded off. Result: 3.14.
You can use the function floor.
This function is rounding off. For example, floor(4.66456) results in: 4.
floor(9.1254) Result 9.
Therefore, to remove two decimal places, you need to multiply by 100 first, then round off, and then divide by 100, that is:
$a=floor(3.149569*100)/100
Calculate the percentage:
Code example:
$successRate = floor((2/3'])*10000)/10000*100; $result = $successRate.'%';
Output result:
66.67%
Method 2, round function
Description
float round ( float val [, int precision])
Returns the result of rounding val according to the specified precision (the number of decimal digits after the decimal point).
precision can also be negative or zero (default).
Example:
Code example:
<?php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.04 echo round(5.055, 2); // 5.06 ?>
Note:
When rounding exactly half of a fraction, round() rounds off even numbers and carries in odd numbers.
If you want to force it to always round to .5 (or .05) in one direction, add or subtract a small factor.
The reason behind rounding off half the value and rounding up the other half is to avoid the traditional banking problem, which is that if rounding is always done the bank takes more money from the customer, and if rounding is always done the bank takes one You will end up losing money.
The average rounding is statistically balanced.
3. sprintfFunction
The last one is to use the sprintf function. Please refer to the article: Introduction to the usage analysis of the sprintf() function in PHP.
Summary:
This article introduces three methods to implement PHP to retain two decimal places. Each method has its own differences. You can Choose the one that suits your needs!
Related recommendations:
PHP method of retaining two decimal places and rounding or not rounding
#php How to use the tailing method to retain two decimal places
JS and php retain two decimal places example rounding Use the function toFixed()
The above is the detailed content of Three ways to retain two decimal places in PHP. For more information, please follow other related articles on the PHP Chinese website!