1

I try to get the difference between two decimals but i need a short number. Example:

var number1 = 1.1500
var number2 = 1.1550
var result = parseFloat(number2) - parseFloat(number1);

This way, i get "0.0050000000000001155" but i just need "0.0050".

Thanks :)

  • The number (not the text) `0.0050` does not exists. So it is impossible to get it. It's a feature/issue of the hardware implementation of floating point numbers. – Wiimm Apr 23 '19 at 08:56

1 Answers1

-1

you can use toFixed(). And you don't need to call parseFloat the numbers are already float

var number1 = 1.1500
var number2 = 1.1550
var result = +(number2 - number1).toFixed(5);
console.log(result)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • Try `result.toPrecision(18)` and you see, that the result is still `0.00500000000000000010`. – Wiimm Apr 23 '19 at 08:54
  • @Wiimm Where to `toPrecision(18)` comes from. I am using `toFixed()` and not using `18` anywhere? – Maheer Ali Apr 23 '19 at 09:18
  • Knowledge about floating point numbers (IEEE 754) and Javascript: `toPrecision(18)` shows a floating point number exact as possible. `toFixed()` is an output function that returns a string and not a number, because generally no exact number exists that will reflect the result of `toFixed()`. Converting the result to a number will binary round it to the nearest possible floating point number. And `toPrecision(18)` shows this number. – Wiimm Apr 23 '19 at 11:27