Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails number_to_currency delete trailing zeroes right of decimal

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.

like image 372
ctilley79 Avatar asked May 20 '15 18:05

ctilley79


2 Answers

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.

like image 101
andreanne.wintheiser Avatar answered Sep 30 '22 19:09

andreanne.wintheiser


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

like image 41
dandlezzz Avatar answered Sep 30 '22 18:09

dandlezzz