Problem:
You have a number (ex. 549.767, 549, or .549). You want to round the number to 2 decimal places (ex. 549.77, 549.00, or 0.55).
Solution:
You can do it in few ways.
Method 1: Using number_format() function
Using number_format(), you can format a number. The first parameter of the function is the number to be formatted. The second parameter formats the first parameter with the number of decimals it shows and add a dot in front of it.
In the following example below, each number will be rounded to the 2 decimal places after the dot.
<?php $number = 549.767; echo number_format($number, 2). "<br />"; $number = 549;echo number_format($number, 2) . "<br />"; $number = .549;echo number_format($number, 2); ?>
[wpdm_file id=73]
Output:
549.77
549.00
0.55
Method 2: Using round() function
round() function rounds the first parameter (which is a float) to the number of digits after decimal point mentioned by the second parameter.
<?php $number = 549.767; echo round($number, 2). "<br />"; $number = 549; echo round($number, 2). "<br />"; $number = .549; echo round($number, 2). "<br /><br />"; ?>
[wpdm_file id=74]
Output:
549.77
549
0.55
Note: As round() function rounds floats, the number 549 above has not been formatted with decimal point.
Method 3: Using sprintf() function
sprintf() function can change the format of a number to another. The first parameter of this function sets the rules on how to format a number and the second parameter is the number itself.
The first parameter which is called format specifier starts with a percentage (%) sign. Then the dot and the 2 comes which is precision specifier that tells 2 decimal digits should be displayed after the dot. The f at last tells to treat the number as a float.
<?php $number = 549.767; $number = sprintf('%.2f', $number). "<br />"; echo $number; $number = 549; $number = sprintf('%.2f', $number) . "<br />"; echo $number; $number = .549; $number = sprintf('%.2f', $number) . "<br /><br />"; echo $number; ?>
[wpdm_file id=75]
Output:
549.77
549.00
0.55
Method 4: Using printf() function
printf() function works similarly to the sprintf() function except that the printf() function prints a number directly to the screen, on the other hand, sprint() function allows you to save the formatted number to a variable.
See the code below-
<?php $number = 549.767; printf('%.2f', $number); echo "<br />"; $number = 549; printf('%.2f', $number);echo "<br />"; $number = .549;printf('%.2f', $number); echo "<br />"; ?>
[wpdm_file id=76]
Output:
549.77
549.00
0.55