to_d to always return 2 decimals places in ruby

后端 未结 5 1913
你的背包
你的背包 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 06:42

    Here's a hint. 500.00 is a representation of the number 500.0

    Specifically, sprintf will help you:

    irb(main):004:0> sprintf "%.2f", 500.0
    => "500.00"
    
    0 讨论(0)
  • 2020-12-08 06:47

    In addition to mcfinnigan's answer, you can also use the following to get 2 decimal places

    '%.2f' % 500 # "500.00"
    

    This use case is known as the string format operator

    0 讨论(0)
  • 2020-12-08 06:56

    Do not use floating point numbers to represent money. See this question for a good overview of why this is a bad idea.

    Instead, store monetary values as integers (representing cents), or have a look at the money gem that provides lots of useful functionality for dealing with such values.

    0 讨论(0)
  • 2020-12-08 06:56

    There was a requirement to round DOWN.

    Most other answers round 500.016 UP to 500.02

    Try:

    def self.round_down(x, n = 2)
      "%.#{n}f" % x.to_d.truncate(n)
    end
    
    irb(main):024:0> x=500.0; '%.2f' % x.to_d.truncate(2)
    => "500.00"
    irb(main):025:0> x=500.016; '%.2f' % x.to_d.truncate(2)
    => "500.01"
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题