to_d to always return 2 decimals places in ruby

后端 未结 5 1932
你的背包
你的背包 2020-12-08 06:01

I\'m dealing with currencies and I want to round down the number to 2 decimal places. Even if the number is 500.0, I would like it to be 500.00 to be consistent. When I do \

5条回答
  •  死守一世寂寞
    2020-12-08 07:00

    Since you are using Rails and this seems to be related to a view, there's number_with_precision:

    number_with_precision(500, precision: 2)
    #=> "500.00"
    
    I18n.locale = :de
    number_with_precision(500, precision: 2)
    #=> "500,00"
    

    For currencies I'd suggest number_to_currency:

    number_to_currency(500)
    #=> "$500.00"
    

提交回复
热议问题