- how do i round in php with keeping the two zeros
- Округление чисел в PHP
- Округление к ближайшему целому
- Округление к большему
- Rounding numbers with PHP
- round()
- ceil()
- floor()
- number_format()
- printf() and sprintf()
- Check Out These Related posts:
- Show a Number to Two Decimal Places in PHP
- Use number_format() Function to Show a Number to Two Decimal Places in PHP
- Use round() Function to Show a Number to Two Decimal Places in PHP
- Use sprintf() Function to Show a Number to Two Decimal Places in PHP
- Related Article — PHP Number
how do i round in php with keeping the two zeros
Just be aware that (AFAIK) this is locale aware, and that with certain setups it may output 1,00 — though I may be mistaken here.
To be safe use number_format($price, 2, ‘.’, »); so your number isn’t effected by locale or thousand separators.
The following printf() call should work for you:
The documentation for this syntax is best described on the sprintf() page.
@FakeCodeMonkeyRashid it happens in the call to round() and then when printing it, it is formatted to have exactly 2 trailing decimals.
@nickf: Tim should have touched on that briefly. What happens if the PHP documentation is offline when someone looks at this answer?
If you want the rounding to be accurate (which i imagine you would do) i would never use printf() . printf(‘%.2f | %.2f | %.2f | %.2f’, 1.005, 1.015, 1.025, 1.035); outputs 1.00 | 1.01 | 1.02 | 1.03 (instead of 1.01 | 1.02 | 1.03 | 1.04) and printf(‘%.3f | %.3f | %.3f | %.3f’, 1.0005, 1.0015, 1.0025, 1.0035); outputs 1.000 | 1.002 | 1.002 | 1.004 (instead of 1.001 | 1.002 | 1.003 | 1.004). I use either number_format($x, 2); (remembering this is locale aware) or printf(‘%.2f’, round($x, 2));
@PeterM The OP refers to $price, so if talking about currency i wouldn’t say it’s a matter of personal preference when it comes to rounding. If a company gets overcharged because the developer prefers to round up, i don’t think that would go down too well!
Округление чисел в PHP
В PHP для округления чисел применяются следующие функции:
Округление к ближайшему целому
Функция round($num, $precision) возвращает округлённое значение $num с указанной точностью $precision (количество цифр после запятой).
echo round(111.455); // 111 // Один знак после запятой echo round(111.455, 1); // 111.5 // Два знака после запятой echo round(111.455, 2); // 111.46
Также функция round() может округлять целую часть числа, для этого нужно указать отрицательный $precision .
// Один знак перед запятой echo round(111.455, -1); // 110 // Два знака перед запятой echo round(111.455, -2); // 100
Третьим аргументом функции можно повлиять способ округления.
PHP_ROUND_HALF_UP | Округляет от нуля, когда следующий знак находится посередине. То есть округляет 1.5 в 2 и -1.5 в -2. |
PHP_ROUND_HALF_DOWN | Округляет к нулю, когда следующий знак находится посередине. То есть округляет 1.5 в 1 и -1.5 в -1. |
PHP_ROUND_HALF_EVEN | Округляет до ближайшего чётного значения, когда следующий знак находится посередине. То есть округляет 1.5 и 2.5 в 2. |
PHP_ROUND_HALF_ODD | Округляет до ближайшего нечётного значения, когда следующий знак находится посередине. То есть округляет 1.5 в 1 и 2.5 в 3. |
Округление к большему
Функция ceil($num) – всегда округляет число в большую сторону.
echo ceil(1.1); // 2 echo ceil(1.5); // 2 echo ceil(1.6); // 2
Rounding numbers with PHP
I have previously looked at rounding numbers with MySQL and Javascript and in this post look at rounding numbers with PHP using the round() ceil() floor() number_format() and s/printf() functions.
round()
The round() function rounds the number passed in to the specified number of decimal places. If the decimal places is a negative number then the numbers to the left of the decimal place are rounded. If the decimal places parameter is not passed in then it defaults to zero and will round as an integer. 5 is round up and < 5 is rounded down.
echo round(153.751, 2); // 153.75 echo round(153.751, 1); // 153.8 echo round(153.751); // 154 echo round(153.751, -1); // 150 echo round(153.751, -2); // 200
From PHP 5.3.0 round() accepts a 3rd parameter can be passed which specifys the rounding mode and is one of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD. It defaults to PHP_ROUND_HALF_UP to maintain backward compatibility.
ceil()
The ceil() function rounds up to the nearest integer (ceil = ceiling). There is no argument for precision so it will always round up to the nearest integer. If the number is already an integer then the value returned will remain the same.
echo ceil(153.251); // 154 echo ceil(153.751); // 154 echo ceil(-153.251); // -153 echo ceil(-153.751); // -153
floor()
The floor() functuon works the same was as ceil() but always rounding down to the nearest integer. Some examples:
echo floor(153.251); // 153 echo floor(153.751); // 153 echo floor(-153.251); // -154 echo floor(-153.751); // -154
number_format()
The PHP number_format() function is used for formatting numbers with decimal places and thousands separators, but it also rounds numbers if there are more decimal places in the original number than required. As with round() it will round up on 5 and down on < 5.
echo number_format(153.751); // 154 echo number_format(153.751, 1); // 153.8 echo number_format(153.751, 2); // 153.75
printf() and sprintf()
The printf() and sprintf() functions are also for formatting and again will round numbers as well. printf() outputs the value to standard output whereas sprintf() returns it as a value.
printf("%0.2f", 153.751); // 153.75 printf("%0.1f", 153.751); // 153.8 printf("%d", 153.751); // 153
Check Out These Related posts:
Show a Number to Two Decimal Places in PHP
- Use number_format() Function to Show a Number to Two Decimal Places in PHP
- Use round() Function to Show a Number to Two Decimal Places in PHP
- Use sprintf() Function to Show a Number to Two Decimal Places in PHP
In this article, we will introduce methods to show a number to two decimal places in PHP.
Use number_format() Function to Show a Number to Two Decimal Places in PHP
The built-in function number_format() is used to format a number. By formatting, we mean that the number is displayed with a decimal point and a thousand separator. It also rounds a number if needed. We can use this function to show a number to two decimal places. The correct syntax to use this function is as follows
number_format($number, $NumOfDecimals, $decimalIndicator, $thousandSeparator)
php $number1 = 5; $number2 = 34.600; $number3 = 15439.093; $format_number1 = number_format($number1, 2); $format_number2 = number_format($number2, 2); $format_number3 = number_format($number3, 2, "d", "@"); echo "The number $number1 after formating is: $format_number1 \n"; echo "The number $number2 after formating is: $format_number2 \n"; echo "The number $number3 after formating is: $format_number3 \n"; ?>
This function has three optional parameters but it does not allow three parameters. It allows one, two, and four parameters to be passed. In this example, the $number1 and $number2 are formatted to two decimal places with the default decimal point. But $number3 is formatted with custom decimal point «d» and thousand separator «@» .
The number 5 after formating is: 5.00 The number 34.6 after formating is: 34.60 The number 15439.093 after formating is: 15@439d09
Use round() Function to Show a Number to Two Decimal Places in PHP
The round() function is used to round a number or float value. We can round a number to our desired decimal places. The correct syntax to use this function is as follows
round($number, $decimalPlaces, $mode);
php $number1 = 5; $number2 = 34.6; $number3 = 15439.093; $format_number1 = round($number1, 2); $format_number2 = round($number2, 2); $format_number3 = round($number3, 2); echo "The number $number1 after rounding is: $format_number1 \n"; echo "The number $number2 after rounding is: $format_number2 \n"; echo "The number $number3 after rounding is: $format_number3 \n"; ?>
The important thing to note here is that it does not affect a number or a float value with one decimal point if we want to round these to two decimal places.
The number 5 after rounding is: 5 The number 34.6 after rounding is: 34.6 The number 15439.093 after rounding is: 15439.09
When the original number has fewer decimal digits than the decimal places to be formatted, round() function will not add zeros at the end of the number.
You should use the number_format() method if two decimal places are needed for all numbers including integers.
Use sprintf() Function to Show a Number to Two Decimal Places in PHP
The built-in function sprintf() formats a string according to a given format. It can be used to show a number to two decimal places. The correct syntax to use this function is as follows
sprintf($format, $parameter1, $parameter2, . , $parameterN);
The parameter $format is the format that specifies how the variables will be in the string. The next parameter $parameter1 is the first variable whose value will be assigned to the first % in the string. The parameter $parameter2 is the second variable whose value will be assigned to the second % in the string. In this way, we can insert N variables for N % signs.
php $num = 67; $number = sprintf('%.2f', $num); echo "The number upto two decimal places is $number"; ?>
Here, we have used %f for a float value. %.2f indicates that the float value will be up to two decimal places.
The number up to two decimal places is 67.00