0

Few Multiplications are not working as expected.

Expected: No Decimal part.

enter image description here

But few multiplications are working as expected.

enter image description here

Is there a JS explanation behind this?

My fix:

I used Math.trunc() to always have an integral part after multiplication. But I hope this shouldn't be required by default.

Anjan Talatam
  • 2,212
  • 1
  • 12
  • 26
  • 1
    i's actually not js problem, but processor https://ellenaua.medium.com/floating-point-errors-in-javascript-node-js-21aadd897bf8 – Pasha K Aug 22 '22 at 10:27
  • 1
    Don't use Math.trunc() since that will give you the wrong answer for 4.1*100. Use Math.round(). – Hafthor Aug 22 '22 at 10:46
  • 1
    note that even your 1.2 example probably isn't doing what you expect internally. when you enter that value JS will actually interpret it as 1.1999999999999999555910790149937383830547332763671875. when you multiply that by 100 the nearest value that it can represent happens to be 120, which is why it seems to be "working as expected" – Sam Mason Aug 22 '22 at 10:58
  • Hi @SamMason, Can you tell me how exactly have you arrived at this number? 1.1999999999999999555910790149937383830547332763671875 I am trying a few things but can't get to this number. – Anjan Talatam Aug 22 '22 at 12:41
  • 1
    I used Python's `decimal` module, but https://baseconvert.com/ieee-754-floating-point looks nice as well – Sam Mason Aug 22 '22 at 12:56
  • 1
    if you prefer to stay in JS, that link seems to use https://mikemcl.github.io/bignumber.js/ to do arbitrary precision where I used `decimal` – Sam Mason Aug 22 '22 at 13:04

0 Answers0