11

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

Community
  • 1
  • 1
crystal
  • 123
  • 1
  • 1
  • 4

2 Answers2

26

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

Mark
  • 6,731
  • 1
  • 40
  • 38
  • 1
    This is not true. When you calculate different numbers, you will get same error. E.g. (6.41 * 10 - 1.61 * 10) / 10 = 4.799999999999999 The corrent solution is: (6.4 - 1.6 ).toFixed(2) (2 is the decimals count) – Mumin Ka Nov 08 '18 at 08:11
  • 1
    @MuminKa _convert to integer_ in your case means `(6.41 * 100 - 1.61 * 100) / 100 = 4.8`. The question asked for solutions without using toFixed(). – Mark Nov 08 '18 at 23:02
  • I'm sorry I didn't see the actual demand :() @Mark – Mumin Ka Nov 09 '18 at 08:37
6

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.

Community
  • 1
  • 1
apsillers
  • 112,806
  • 17
  • 235
  • 239