Rounding float in Ruby

后端 未结 9 1175
北恋
北恋 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
    
    0 讨论(0)
  • 2020-12-12 13:41

    If you just need to display it, I would use the number_with_precision helper. If you need it somewhere else I would use, as Steve Weet pointed, the round method

    0 讨论(0)
  • 2020-12-12 13:43

    For ruby 1.8.7 you could add the following to your code:

    class Float
        alias oldround:round
        def round(precision = nil)
            if precision.nil?
                return self
            else
                return ((self * 10**precision).oldround.to_f) / (10**precision)
            end 
        end 
    end
    
    0 讨论(0)
  • 2020-12-12 13:49

    Pass an argument to round containing the number of decimal places to round to

    >> 2.3465.round
    => 2
    >> 2.3465.round(2)
    => 2.35
    >> 2.3465.round(3)
    => 2.347
    
    0 讨论(0)
  • 2020-12-12 13:53

    When displaying, you can use (for example)

    >> '%.2f' % 2.3465
    => "2.35"
    

    If you want to store it rounded, you can use

    >> (2.3465*100).round / 100.0
    => 2.35
    
    0 讨论(0)
  • 2020-12-12 13:56
    def rounding(float,precision)
        return ((float * 10**precision).round.to_f) / (10**precision)
    end
    
    0 讨论(0)
提交回复
热议问题