cwncool Posted February 7, 2007 Share Posted February 7, 2007 I have a simple math problem. When my script adds my two numbers, for example, "0.60" and "0.30", it displays "0.9". Although that is correct, this is dealing with money, so I need it to add up to "0.90". Is there something I can do to make this add always with 2 decimal places? Thanx! Link to comment https://forums.phpfreaks.com/topic/37423-solved-i-need-to-raise-the-decimal-amount-in-a-math-problem/ Share on other sites More sharing options...
hvle Posted February 7, 2007 Share Posted February 7, 2007 echo sprintf("%.2f", 0.9); will echo 0.90 "%.2f" is format of output, number 2 specified the number of decimal to be print Link to comment https://forums.phpfreaks.com/topic/37423-solved-i-need-to-raise-the-decimal-amount-in-a-math-problem/#findComment-178886 Share on other sites More sharing options...
btherl Posted February 7, 2007 Share Posted February 7, 2007 Also, be warned that with large numbers your calculations may not be accurate. If you need to do serious monetary calculations, you should avoid using floating point numbers. Link to comment https://forums.phpfreaks.com/topic/37423-solved-i-need-to-raise-the-decimal-amount-in-a-math-problem/#findComment-178974 Share on other sites More sharing options...
cwncool Posted February 7, 2007 Author Share Posted February 7, 2007 Also, be warned that with large numbers your calculations may not be accurate. If you need to do serious monetary calculations, you should avoid using floating point numbers. What'd you mean? Link to comment https://forums.phpfreaks.com/topic/37423-solved-i-need-to-raise-the-decimal-amount-in-a-math-problem/#findComment-179540 Share on other sites More sharing options...
cwncool Posted February 8, 2007 Author Share Posted February 8, 2007 Well, I ended up using "number_format($total, 2);" It works fine. Thanks for the help! Link to comment https://forums.phpfreaks.com/topic/37423-solved-i-need-to-raise-the-decimal-amount-in-a-math-problem/#findComment-179570 Share on other sites More sharing options...
btherl Posted February 8, 2007 Share Posted February 8, 2007 What I mean is this: <? $a = 99999999999.99; print "$a\n"; ?> On my system this prints out 100000000000. As long as you only use small values, and you don't do any tricky maths, you should be ok The reason for this is that floating point numbers (numbers with a "." in them) only have limited accuracy. When the numbers are large, they start dropping decimal places in order to store the digits to the left of the dot. Link to comment https://forums.phpfreaks.com/topic/37423-solved-i-need-to-raise-the-decimal-amount-in-a-math-problem/#findComment-179608 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.