gayanp Posted April 18, 2011 Share Posted April 18, 2011 Why it's print -2.8421709430404E-14; <?Php function getDiscount() { $discount = 100; return (245/100) * $discount; } echo 245-getDiscount(); ?> Link to comment https://forums.phpfreaks.com/topic/234031-why-this-return-28421709430404e-14/ Share on other sites More sharing options...
spiderwell Posted April 18, 2011 Share Posted April 18, 2011 edit:: try this: echo 245-(int)getDiscount(); this converts the returned value to a number rather than a string Link to comment https://forums.phpfreaks.com/topic/234031-why-this-return-28421709430404e-14/#findComment-1202882 Share on other sites More sharing options...
gayanp Posted April 18, 2011 Author Share Posted April 18, 2011 Thank you for your replay i cant use echo 245-(int)getDiscount(); Discount can be change to decimal value.. i want value with 2 decimal places. please help me if you have better solution .. Actually i want to get understand why this happen.. check this ... it's return -0.00 it cant be -0.00 i want value 0.00. please help me.. function getDiscount() { $discount =0; $discount = 100; return (245/100) * $discount; } $y =245.00; $x =getDiscount(); echo number_format(($y-$x),2); Link to comment https://forums.phpfreaks.com/topic/234031-why-this-return-28421709430404e-14/#findComment-1202891 Share on other sites More sharing options...
ignace Posted April 18, 2011 Share Posted April 18, 2011 The reason this happens is due to how a FLOAT is stored in memory. FLOAT has a loss in precision, it actually tells you how big the loss is: -2.8421709430404E-14 Therefor you should use BCMath, which gives you the correct result: print bcsub(245, getDiscount()); // returns: 0 Link to comment https://forums.phpfreaks.com/topic/234031-why-this-return-28421709430404e-14/#findComment-1202912 Share on other sites More sharing options...
spiderwell Posted April 18, 2011 Share Posted April 18, 2011 glad you helped out there ignace, I was about to say to put this in the maths section, as I don't really know the answer. Link to comment https://forums.phpfreaks.com/topic/234031-why-this-return-28421709430404e-14/#findComment-1202914 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.