Skip to content

Instantly share code, notes, and snippets.

@Sammitch
Created December 15, 2016 02:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sammitch/899bf95b424d96dcd58e5f34f3534ab5 to your computer and use it in GitHub Desktop.
Save Sammitch/899bf95b424d96dcd58e5f34f3534ab5 to your computer and use it in GitHub Desktop.
Answer to a StackOverflow question locked by idiots...

Answer for: http://stackoverflow.com/questions/41154976/php-rounding-number-cant-round

Because round() returns a float, and 68.45 can't be accurately represented at high precisions. In this case, 16 digits or higher.

Eg:

function test($number, $precision) {
    ini_set('precision', $precision);
    var_dump(
        $number,
        round($number, 2),
        number_format($number, 2),
        sprintf("%4.2f", $number)
    );
    echo "\n";
}

$a = 68.45999999999999;
$b = 68.46;
echo "== Precision 15 ==\n";
test($a, 15);
test($b, 15);
echo "== Precision 16 ==\n";
test($a, 16);
test($b, 16);

Output:

== Precision 15 ==
float(68.46)
float(68.46)
string(5) "68.46"
string(5) "68.46"

float(68.46)
float(68.46)
string(5) "68.46"
string(5) "68.46"

== Precision 16 ==
float(68.45999999999999)
float(68.45999999999999)
string(5) "68.46"
string(5) "68.46"

float(68.45999999999999)
float(68.45999999999999)
string(5) "68.46"
string(5) "68.46"

Use number_format() or [s]printf() as also illustrated in the example. However, if you are trying to accurately round a float to two digits you really should read up on how floats work...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment