0

I was doing just a simple increment of floating number using PHP Laravel as API, like code below;

Code:

public function testArrIncrement(){
    $arr["test"]["words"] = "The quick brown fox jumps over a lazy dog";
    $arr["test"]["number"] = 0;
    for($i=0; $i<11; $i++) $arr["test"]["number"] += 0.01;
    return response()->json($arr, 200);
}

Result:

{
    "test": {
        "words": "The quick brown fox jumps over a lazy dog",
        "number": 0.10999999999999999
    }
}

the strange thing is, why the value of $arr["test"]["number"] is not 0.11, but instead 0.10999999999999999 ?

But if I tried the same code just using plain single file PHP without any framework everything is normal the value of $arr["test"]["number"] is indeed 0.11.

Code:

$arr["test"]["words"] = "The quick brown fox jumps over a lazy dog";
$arr["test"]["number"] = 0;
for($i=0; $i<11; $i++) $arr["test"]["number"] += 0.01;
var_dump($arr);

Result:

array(1) { ["test"]=> array(2) { ["words"]=> string(41) "The quick brown fox jumps over a lazy dog" ["number"]=> float(0.11) } }

Plese help why this happen??

1 Answer 1

1

It is due to the data being encoded into json. If you try json_encode you will encounter the same behavior which is intended. You have to set precision either in php.ini or in your code like so:

public function testArrIncrement(){
    ini_set('serialize_precision', 14);
    $arr["test"]["words"] = "The quick brown fox jumps over a lazy dog";
    $arr["test"]["number"] = 0;
    for($i=0; $i<11; $i++) $arr["test"]["number"] += 0.01;
    return response()->json($arr, 200);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, first of all Thank You very much that works like a charm. Can You please explain what is serialize_precision and why the value must be 14?
sure, 14 tells the number of significant digits to take after the decimal. Your default seemed to be 17 which was causing rounding errors during serialize errors. We have to provide as close to accurate data as possible when trying to serialize so it rounds off correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.