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,593
  • 4
  • 40
  • 81
Frank
  • 1,802
  • 4
  • 17
  • 37

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));
Always Sunny
  • 32,751
  • 7
  • 52
  • 86
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,105
  • 2
  • 15
  • 36
  • 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