Rounding float in Ruby

后端 未结 9 1206
北恋
北恋 2020-12-12 13:33

I\'m having problems rounding. I have a float, which I want to round to the hundredth of a decimal. However, I can only use .round which basically turns it in

9条回答
  •  我在风中等你
    2020-12-12 13:40

    You can add a method in Float Class, I learnt this from stackoverflow:

    class Float
        def precision(p)
            # Make sure the precision level is actually an integer and > 0
            raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0
            # Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0
            return self.round if p == 0
            # Standard case  
            return (self * 10**p).round.to_f / 10**p
        end
    end
    

提交回复
热议问题