0

Let's say I have some currency value const num = '2.05';. I would like to receive this amount in cents. So the possible solution:

const num = '2.05';
const floatNum = parseFloat(num); // 2.05
floatNum * 100; // 204.99999999999997

The problem here in rounding, expected value 205 not 204.99999999999997. What I can do to resolve this:

const num = '2.05';
return parseInt(num.replace('.', '')); // 205

It will work in most cases but I have doubt that it's fully safe variant. Would be great if someone suggest better method.

Jesse
  • 1,386
  • 3
  • 9
  • 23
Pasha
  • 621
  • 8
  • 21
  • 2
    Can you not just round it back to 2.05? https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary – Sam Walpole Dec 11 '19 at 16:41
  • 2
    Does this answer your question? [Multiplication int and float(double) in JavaScript](https://stackoverflow.com/questions/16608146/multiplication-int-and-floatdouble-in-javascript) – Jesse Dec 11 '19 at 16:46
  • 2
    You can you use round function from Math library: Math.round(parseFloat('2.05') * 100) – Mostafa Babaii Dec 11 '19 at 16:48
  • 2
    Does this answer your question? [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – jtwalters Dec 11 '19 at 16:49

1 Answers1

3

You are looking for Math.round probably :https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-float-

So something like : Math.round(2.05*100) should alway yield 205, then just go %100 to drop the prefix.

Yann TM
  • 1,942
  • 13
  • 22