Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Subtraction problems in javascript [duplicate]

Tags:

javascript

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

like image 212
crystal Avatar asked May 23 '12 05:05

crystal


People also ask

How do I get 2 decimal places in JavaScript?

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.

How do you keep decimals in JavaScript?

JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.

How do you subtract a number in JavaScript?

The subtraction operator ( - ) subtracts the two operands, producing their difference.


2 Answers

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

like image 188
Mark Avatar answered Oct 28 '22 22:10

Mark


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.

like image 43
apsillers Avatar answered Oct 28 '22 22:10

apsillers