0

I am a little bit confused about how JavaScript acts when adding numbers to big numbers. I thought the numbers are too big, but it seems like this is not the case. Broken down the problem to this additions (Google Chrome Dev Console):

enter image description here

What is the reason for this behaviour and how to avoid it?

whocares81
  • 129
  • 1
  • 16
  • Does this answer your question? [Help in double precision addition](https://stackoverflow.com/questions/6093534/help-in-double-precision-addition) – Luatic May 16 '22 at 10:40
  • 2
    "*I thought the numbers are too big, but it seems like this is not the case.*' why do you think it's not the case when you observe a problem that occurs with integers that are too big? – VLAZ May 16 '22 at 10:40
  • @LMD not related to floating point arithmetic. It's a separate issue which concerns integers. – VLAZ May 16 '22 at 10:41
  • 2
    See also [MAX_SAFE_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER); your numbers exceed it. – Luatic May 16 '22 at 10:41
  • 1
    @VLAZ very much related to floating point arithmetic; see e.g. [the JS Number type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number). JS only knows doubles. Even if you use doubles as integers, you're still using doubles (mantissa-exponent) so you get the same precision issues, except the exponent is positive, not negative. – Luatic May 16 '22 at 10:42
  • @LMD so, you think this is a rounding error with fractions? – VLAZ May 16 '22 at 10:43
  • 1
    @VLAZ yes. Basically, the resulting number requires one (mantissa) bit too much, so you lose one bit of integer precision (hence why their addition yields the closest multiple of two). – Luatic May 16 '22 at 10:44
  • 1
    You can fix this by using [the BigInt datatype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) in relatively modern browsers – Taxel May 16 '22 at 10:51
  • 1e16+1..toFixed(0) //10000000000000001 – Will Black May 16 '22 at 10:52
  • 2
    @WillBlack umm, ` + ` results in *string concatenation*. – VLAZ May 16 '22 at 10:53

0 Answers0