Created
May 31, 2011 23:16
-
-
Save mikesherov/1001480 to your computer and use it in GitHub Desktop.
Silly way to round two numbers to the least granular precision PHP
This file contains 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
<?php | |
function dec_points($val){ | |
$precision = 0; | |
while($precision < 10){ | |
if($val == round($val, $precision)){ | |
break; | |
} | |
$precision++; | |
} | |
return $precision; | |
} | |
function dec_points2($val1, $val2){ | |
$precision = min(dec_points($val1),dec_points($val2)); | |
return round($val1 - $val2, $precision); | |
} | |
var_dump(dec_points2(4.5936, 4.59359782)); | |
var_dump(dec_points2(4.5936, 4.59359782000000000000)); | |
var_dump(dec_points2(4.59360000, 4.59359782000000000000)); | |
var_dump(dec_points2(4.593600001, 4.59359782000000000000)); | |
var_dump(dec_points2(4.593600001, 4.59359782)); | |
var_dump(dec_points2(4.593600001, 4.5936)); | |
var_dump(dec_points2(4.59360000001, 4.59359782000000000000)); | |
var_dump(dec_points2(0.59360000001, 4.59359782000000000000)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment