10

I have a dynamically generated table that multiplies price * qty. Some of the prices are in partial cents. For example

if the price of an item is 0.0375 I can display that in my table as

number_to_currency(0.0375,:precision => 4)
=> $0.0375

but on quantities where the price is a standard 2 decimal number I get

number_to_currency(33.95,:precision => 4)
  => $39.9500

I need a way to trim the trailing zeroes of a decimal value. Keep in mind that the output is in a Model.each block so I'm uncertain I can modify the precision parameter conditionally.

ctilley79
  • 2,151
  • 3
  • 31
  • 64

5 Answers5

24

Try to specify strip_insignificant_zeros option:

number_to_currency(33.95, precision: 4, strip_insignificant_zeros: true)

It should remove zeros after decimal separator. Here is description of this option.

1

The default for this method is 2. So you simply need

number_to_currency(33.95)

http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency

dandlezzz
  • 603
  • 6
  • 14
0
number_to_currency(33.95,:precision => 2)
B Seven
  • 44,484
  • 66
  • 240
  • 385
0

Since number_to_currency returns a String, you can use .remove(/0+$/) to remove any trailing zeros:

number_to_currency(33.95,:precision => 4).remove(/0+$/)
infused
  • 24,000
  • 13
  • 68
  • 78
0

Try using round before number_to_currency:

number_to_currency(33.95.round(4)) # $33.95
number_to_currency(0.0375.round(4)) # $0.0375
Undo
  • 25,519
  • 37
  • 106
  • 129
Shalev Shalit
  • 1,945
  • 4
  • 24
  • 34