Possible Duplicate:
Is JavaScript's Math broken?
when i subtract 6.4-1.6 i am getting the answer as 4.800000000000001 in JS, but i need as 4.8 without using toFixed(), toPrecision() and Math.round(). any idea???
Thanks,
crystal
Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.
JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.
The subtraction operator ( - ) subtracts the two operands, producing their difference.
Convert to integers before doing the subtraction to avoid problems with floating point arithmetic:
(6.4 * 10 - 1.6 * 10) / 10
See What Every Programmer Should Know About Floating-Point Arithmetic
This is a well-known limitation of IEEE 754 floating point numbers. See How to deal with floating point number precision in JavaScript? for solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With