0

Scenario: On my server a stripe payment intent is created for customer orders. The amount needs to be multiplied by 100 to meet stripes format. The problem is the amount of the order is always different and isn't always a whole integer.

When I am doing say:

const amount = 323.78 * 100

I do not get the answer I need, I get 32377.999999999996, when I need 32,378. I have learned JS is notorious for this. Is there a way to work around this?

stinny
  • 147
  • 1
  • 12
  • `Number(amount.toFixed(2))` would give a number to 2 decimal places.. you can turn `2` into any other number in order to get more precision – The Bomb Squad Oct 18 '22 at 00:16
  • 2
    Nothing to do with JS, btw. Use integers at all times for currency (which is what Stripe is even encouraging you to do). – Ry- Oct 18 '22 at 00:26
  • 2
    Javascript is not 'notorious' for this, any more than any other language handling floating point arithmetic. It's a function of the way floating point maths works in computers. The way to work around it is to do all your calculations in base units (cents, or pence or whatever you work in) and divide the result by 100 for display. Thus, you can work almost entirely in integers and these rounding problems don't arise – Tangentially Perpendicular Oct 18 '22 at 00:27
  • yea it's a binary problem I forgot to mention ;-; – The Bomb Squad Oct 18 '22 at 00:27
  • When precision matter, always store your value and perform arithmetic as integer, using the smallest granularity as the unit. – Ricky Mo Oct 18 '22 at 01:52

0 Answers0