Rails number_to_currency delete trailing zeroes right of decimal
Asked Answered
D

5

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.

Denigrate answered 20/5, 2015 at 18:8 Comment(0)
C
25

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.

Confinement answered 20/5, 2015 at 18:16 Comment(1)
Thank you! This answer met my requirements since number_to_currency is inside a loop.Denigrate
S
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

Shipmate answered 20/5, 2015 at 18:16 Comment(0)
Q
0
number_to_currency(33.95,:precision => 2)
Quickie answered 20/5, 2015 at 18:14 Comment(0)
G
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+$/)
Guillory answered 20/5, 2015 at 18:15 Comment(0)
L
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
Lenard answered 20/5, 2015 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.