2013-07-05 37 views
2

嘿,我正在使用Ruby on Rails框架,並且我有一個十進制的價格變量。當然價值像39.99美元罰款,但當價格是39.90美元我的應用程序顯示價格爲39.9美元我怎麼能改變這一點。在Ruby中將十進制轉換爲價格格式

我的觀點

%B價格

= @ product.price

回答

4

導軌包括number_to_currency(@product.price)助手。更簡單,更容易記住。

1

這裏的標準答案是使用sprintf

sprintf("$%2.2f", @product.price) 

這將使用前導美元符號格式化數字,然後將數字格式化爲小數點後兩位。

1

如果你願意,你可以編寫你的自定義幫助器方法。

def num_to_currency price 
    "$#{price.to_i}."+"#{(price % 1.0)}"[2..3] 
end 

1.9.3 (main):0 > num_to_currency 6.90 
=> "$6.90" 
相關問題