Floating point rounding error & how to overcome?
Posted: Mon Oct 24, 2011 11:23 pm
This is probably somewhat rare but I've noticed that using a number with 7 decimal places in any sort of calculation yields a number (prior to the calculation) that is rounded. For example:
answer round("29.9999999",7) * 1 yields an answer of 30 -- (seven decimal places)
-whereas-
answer round("29.999999",7) * 1 yields an answer of 29.999999 -- (six decimal places)
(I can increase the precision argument from 7 to 15 and it makes no difference.)
Note that using the trunc() function yields an answer of 30 for the first example but 29 for the second.
I've been using the offset function to determine if there is a decimal point present in the string provided by the user and, if so, then truncate the -string- down to the integer portion; then I may use the integer portion that remains in whatever calculations are necessary.
Is there an easier way to, perhaps, simply set the precision high enough where I can simply use the trunc() function for all numbers a user could possible enter (within reason)?
Thanks,
Barry
answer round("29.9999999",7) * 1 yields an answer of 30 -- (seven decimal places)
-whereas-
answer round("29.999999",7) * 1 yields an answer of 29.999999 -- (six decimal places)
(I can increase the precision argument from 7 to 15 and it makes no difference.)
Note that using the trunc() function yields an answer of 30 for the first example but 29 for the second.
I've been using the offset function to determine if there is a decimal point present in the string provided by the user and, if so, then truncate the -string- down to the integer portion; then I may use the integer portion that remains in whatever calculations are necessary.
Is there an easier way to, perhaps, simply set the precision high enough where I can simply use the trunc() function for all numbers a user could possible enter (within reason)?
Thanks,
Barry