1

I know it's probably due to some sort of rounding technique, but clearly 6.53 + 8 should only equal 14.53. My questions are, why is this happening, and how can I get an accurate sum?

var x = 6.53 + 8;
console.log(x);// 14.530000000000001
richbai90
  • 4,994
  • 4
  • 50
  • 85
Frank
  • 2,050
  • 6
  • 22
  • 40

2 Answers2

3

It is normal behavior with JS, Try to use toFixed(2) like this

var x = 6.53 + 8;
console.log(x.toFixed(2));
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
2

Decimal point numbers are represented differently in a computer...and have this problem..u can have that happen in many programming languages...round your number to a certain precision...as long as you don't do advanced computation with JavaScript you will be fine. More info. https://www.w3schools.com/js/js_numbers.asp

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
  • I used `parseFloat(eval(equation_string).toPrecision(10));` and it works well. I'm making a calculator program for fun and ran into this issue. – Frank Dec 30 '17 at 01:28