0

I don't know why this is so difficult, I am clearly using the wrong methods. But I am working with the Stripe API (everything works well) and I am trying to round a subscription amount to two decimal places.

For example, Stripe forces me to use cents as the unit of currency. So if I have a 995 cents subscription, I clearly want it to show up as $9.95. But the method I am using (number_with_precision (995 / 100, :precision => 2) is giving me 9.00 instead of 9.95. Then I tried the "round" method and it too gives me 9.00.

I see a few rounding posts here on StackOverflow but I can't seem to find anything that solves my convert to dollars/cents then round to 2 decimal places issue.

Any help on this would be appreciated. Thanks in advance for your time.

thenextmogul
  • 1,143
  • 2
  • 10
  • 20

2 Answers2

3

You just need to pass a correct datatype into helper.

Instead of feeding it Integer instance (995 / 100 gives you integer 9), pass a Float instance (995 / 100.to_f, which gives you Float 9.95):

number_with_precision (995 / 100.to_f, precision: 2) # or 995 / 100.0
#=> 9.95
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
1

You can try to use 995 / 100.00 (Python also has this behavior).

As you are using Integer / Integer => Integer. Doing a Integer / Float => Float.