0

Might somebody already faced with calculation issue like in snippet below. First console command shows useless digits after calculation 10.1 +20.1 should be 30.2 but calculated as 30.200000000000003. and second one 10.2 + 20.2=30.4 is correct. There can be a lot of such decimal pairings which creates additional decimals in summ. Why does it happends and hove to avoid it?

console.log(10.1 + 20.1);
console.log(10.2 + 20.2);
Asturion
  • 146
  • 1
  • 3
  • Please see floating point arithmetic in computer science and programming languages. See this https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript Possible duplicate of many questions in many different tags. – aksappy May 26 '21 at 13:29

1 Answers1

2

This looks like a duplicate of How to deal with floating point number precision in JavaScript?.

You can use .toFixed(2) to always get a number with only 2 decimals. https://www.w3schools.com/jsref/jsref_tofixed.asp

More info: https://www.w3schools.com/js/js_numbers.asp

EVeras
  • 324
  • 1
  • 4
  • thx for your reply, but in my calculation's i don't need rounding. I need final accuracy as much as possible, so if it will be 10 or 15 decimals after separator it's ok for me. Looks like it better to make ajax call and perform math operations in php and just return result back. – Asturion May 27 '21 at 05:46