How to not lose precision on division and multiplication?

Viewed 758

I have operation like this:

const amount = 100;
const rate = 0.32123;

const a = amount * rate;
a // 32.123000000000005
const b = a / rate;
b // 100.00000000000001

I need numbers to be the same after convert. How can i achieve this? Both way convert is required. I have many currencies. Each currency have convert rate for internal currency (lets call it myCurr). I cannot convert immediately one currency into another (except internal) because i have convert ratings only for internal currency. So i need firstly convert currency A to internal currency (A * rate1) then i need to convert A to target currency by dividing it to rate2. But doing so, sometimes leads to lose precision. Is there any alternative for amount * rate1 / rate2?

2 Answers

You can never make sure a floating point number stays the same after using it with any arithmetic operation and its reverse operation.

The reason for this:

Floats cover a huge range of numbers - that is why they are way less precise than integers.

Consequences

  • If you want precision, use whole numbers (round them), if not, use floats.

  • Never compare if two floating point numbers are equal. If you compare them, check if they are close. Define a maximum tolerance. If the difference of the numbers is smaller than this tolerance, consider the numbers equal. (Math.abs(amount - b) <= tolerance)

you can use Math.floor or double tilde(~~). both of these would get you what you want.

const amount = 100;
const rate = 0.32123;
const a = amount * rate;
const b = a / rate;
const t = ~~b;
const tt = Math.floor(b);
Related