-2

If @service.amount is equal to $28.95:

<p><%= number_to_currency(@service.amount) %></p>

is outputting $2895.00, not what I wrote above. After searching, I didn't find a solution.

@service.amount is an integer because Stripe only accepts integers.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Grasshopper27
  • 113
  • 1
  • 11
  • 1
    Seems like `@service.amount` is actually `2895`. It's not unusual to store monetary values as cents – it avoids floating point errors. If this is the case, you can get the expected result by dividing the value by 100: `number_to_currency(@service.amount.fdiv(100))` – Stefan Jun 03 '20 at 16:05
  • Thats it! Post your comment as an answer and I'll mark it as accepted. Thanks! – Grasshopper27 Jun 03 '20 at 16:15

2 Answers2

3

Stripe stores values as cents. From the docs:

Zero-decimal currencies

All API requests expect amounts to be provided in a currency’s smallest unit. For example, to charge 10 USD, provide an amount value of 1000 (i.e., 1000 cents).

I assume that the API responses work alike.

To get the correct output, you have to divide the USD value by 100, e.g.:

<%= number_to_currency(@service.amount.fdiv(100)) %>

There's also the Money gem which might be a better alternative. It stores both, the value (as cents) and its currency, and comes with formatting:

require 'money'

money = Money.new(@service.amount, @service.currency)
#=> #<Money fractional:2895 currency:USD>

money.format
#=> "$28.95"
Stefan
  • 109,145
  • 14
  • 143
  • 218
1

number_to_currency does not expect to get amount in cents. It thinks it is in dollars. What you have to do is convert amount in cents to dollars and then send it to number_to_currency method.

I don't know what object is @service but you should be be able to create another method called amount_in_dollars:

def amount_in_dollars
  amount / 100.to_d
end

and then use it in number to currency method:

<p><%= number_to_currency(@service.amount_in_dollars) %></p>

or you could divide it directly in the view (but I would prefer the first variant)

<p><%= number_to_currency(@service.amount / 100.to_d) %></p>
edariedl
  • 3,234
  • 16
  • 19
  • Thanks for responding, but @Stefan got to it two minutes before you posted and it worked. I'll still try yours here and let you know if it works. – Grasshopper27 Jun 03 '20 at 16:16
  • For everyone's information, I tried both of the above suggested approaches and both worked. Use those if you prefer. I only offered to mark @Stefan's comment as accepted simply because he offered it first, not because it's better or worse than this one. But thanks, I appreciate it! :) – Grasshopper27 Jun 03 '20 at 16:24
  • @Grasshopper27 feel free to accept whatever you like :-) – Stefan Jun 03 '20 at 16:33