3

Came across a weird result in Javascript (actually python as well)

var a = 80.1
var b = 100
var a/b = 0.8009999999999999

var a = 80.1
var b = 100
var a*b = 8009.999999999999

Same does not happen for 80.2

Would like to know why this happens

Pranjal
  • 796
  • 1
  • 8
  • 24
  • 1
    Well, you have the answer in your title - "float". That's just how it works. In short, the number is stored in scientific notation using binary base. Therefore not all numbers can be accurately represented, and due to the choice of the base, tenths cannot be accurately represented. Different languages mask this issue differently, some may round the result or just round the displayed number, some simply don't handle it. – IS4 Sep 12 '17 at 10:59
  • 1
    https://stackoverflow.com/questions/588004/is-floating-point-math-broken Also you can get by using Math libraries: https://github.com/MikeMcl/decimal.js – Emil S. Jørgensen Sep 12 '17 at 10:59

1 Answers1

0

The mathematical representation used by JavaScript is in IEEE 754 so there are not all numbers that can be represented with IEEE 754. If you want to perform the division and get the proper result then you need to use the rounding of the decimal values like,

var a = 80.1;
var b = 100;
console.log((a/b).toFixed(3));
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62