PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
Mr_Plough
Forum Newbie
Posts: 3 Joined: Tue Jan 10, 2006 1:27 pm
Post
by Mr_Plough » Sun Apr 16, 2006 10:50 am
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.
Oren
DevNet Resident
Posts: 1640 Joined: Fri Apr 07, 2006 5:13 am
Location: Israel
Post
by Oren » Sun Apr 16, 2006 10:56 am
The script works fine for me.
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Sun Apr 16, 2006 11:17 am
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