Skip to content

Instantly share code, notes, and snippets.

@mikesherov
Created May 31, 2011 23:16
Show Gist options
  • Save mikesherov/1001480 to your computer and use it in GitHub Desktop.
Save mikesherov/1001480 to your computer and use it in GitHub Desktop.
Silly way to round two numbers to the least granular precision PHP
<?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