PHP Tricks
September 2, 2022
How round number up to second digit?
The problem: below numbers should be rounded as described
1256 »» 1300 1200,98 »» 1300 138 »» 140 11,01 »» 12
For solve this problem we can use log10 function in next way:
<?php function myRound($n) { $d = (int)log10($n) - 1; return ceil($n/10**$d) * 10**$d; }
printf ("%d >> %d" . PHP_EOL, 1256, myRound(1256)); printf ("%d >> %d" . PHP_EOL, 1200.98, myRound(1200.98)); printf ("%d >> %d" . PHP_EOL, 138, myRound(138)); printf ("%d >> %d" . PHP_EOL, 11.001, myRound(11.001));
1256 >> 1300 1200 >> 1300 138 >> 140 11 >> 12