Page 1 of 1

Problems Incrementing by 0.1

Posted: Sun Apr 16, 2006 10:50 am
by Mr_Plough
This could be a really simple problem but maths is not my strong point. I have the following code that loops from 0 to 100 in steps of 0.1

Code: Select all

<?php

for ($i=0; $i<100; $i+= 0.1){
        echo $i . "<br />\n";
}

?>
Which works fine until the number after 54.1 - it comes out as 54.200000000001

Can anyone shed some light on this? I know that I could simply round the number but would like to understand what's going on first.

Cheers in advance. :)

Posted: Sun Apr 16, 2006 10:56 am
by Oren
The script works fine for me.

Posted: Sun Apr 16, 2006 11:17 am
by feyd
Floating point arithmetic error. This is a normal side effect of compounding operations on floating point numbers. If you need precision, use bc.

viewtopic.php?t=37751 may be of interest.

d11wtq | /notices nice new avatar of feyd's ;)

Posted: Sun Apr 16, 2006 2:25 pm
by Mr_Plough