Created
October 27, 2012 02:14
-
-
Save zhuzhuaicoding/3962690 to your computer and use it in GitHub Desktop.
PHP: Round to the Nearest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| The common practice of rounding, namely the round() function in PHP, is to round to the nearest decimal point, that is, 1.0, 2.0, 3.0, etc. or, 10, 20, 30, etc. For example, | |
| echo round(4.25, 0); // 4 | |
| echo round(3.1415926, 2); // 3.14 | |
| echo round(299792, -3); // 300000 | |
| When I’m trying to aggregate all the customer ratings for a specific provider in one of my web hosting reviews community, I want to round the average rating to the nearest 0.5 (half the decimal) so that a half star would be correctly displayed. | |
| This is more of a mathematical problem than a PHP one. After some thinking and testing, I came up with a slightly more sophisticated solution than but the round() function: | |
| echo round(1.7 * 2) / 2; // 1.5 | |
| echo round(2.74 * 2) / 2; // 2.5 | |
| echo round(2.75 * 2) / 2; // 3.0 | |
| echo round(3.1 * 2) / 2; // 3.0 | |
| http://www.kavoir.com/2012/10/php-round-to-the-nearest-0-5-1-0-1-5-2-0-2-5-etc.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
working in 2021 php 7.4
source: https://stackoverflow.com/questions/4483540/show-a-number-to-two-decimal-places