-2

In my project, when I am subtracting 96.74 from 60, javascript is giving me 36.739999999999995 , but I need 36.74 to do further calculation.

What should I do, how do I overcome this problem??

Thanks in advance.

Spectric
  • 27,594
  • 6
  • 14
  • 39
ratnesh
  • 365
  • 1
  • 4
  • 14

2 Answers2

1

Example how to round to two decimals, if that was what you wanted?

 var x = 36.739999999999995;

 x = Math.round(x*Math.pow(10,2))/Math.pow(10,2);

 console.log(x);
Filip Huhta
  • 1,359
  • 2
  • 15
  • thanks, it worked for this case, but I am performing this operation on a array and not all numbers have 2 precision after decimal. I will test with different data sets and let you know – ratnesh May 12 '21 at 14:54
1

Use parseFloat and set the decimal places to 2 with .toFixed(2)

console.log(parseFloat(36.739999999999995).toFixed(2))

If you want to get rid of trailing zeroes cast the result to a Number:

var num = Number(parseFloat(36.7).toFixed(2));
console.log(num);
Spectric
  • 27,594
  • 6
  • 14
  • 39
  • thanks, it worked for this case, but I am performing this operation on a array and not all numbers have 2 precision after decimal. I will test with different data sets and let you know – ratnesh May 12 '21 at 14:53