首页 文章

在Ruby中舍入浮点数

提问于
浏览
136

我有问题四舍五入 . 我有一个浮点数,我想要舍入到十进制的十分之一 . 但是,我只能使用 .round ,这基本上把它变成了一个int,意思 2.34.round # => 2. 是否有一种简单的效果方式来做 2.3465 # => 2.35 这样的事情

9 回答

  • 169

    将参数传递给包含要舍入的小数位数的round

    >> 2.3465.round
    => 2
    >> 2.3465.round(2)
    => 2.35
    >> 2.3465.round(3)
    => 2.347
    
  • 7
    def rounding(float,precision)
        return ((float * 10**precision).round.to_f) / (10**precision)
    end
    
  • 3

    你可以在Float类中添加一个方法,我从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
    
  • 1

    如果你只需要显示它,我会使用number_with_precision助手 . 如果你需要它,我会使用,就像Steve Weet指出的那样, round 方法

  • 6

    您还可以提供负数作为 round 方法的参数,以舍入到最接近的10,100的倍数,依此类推 .

    # Round to the nearest multiple of 10. 
    12.3453.round(-1)       # Output: 10
    
    # Round to the nearest multiple of 100. 
    124.3453.round(-2)      # Output: 100
    
  • 2

    对于ruby 1.8.7,您可以在代码中添加以下内容:

    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

    (2.3465*100).round()/100.0 怎么样?

  • 3

    显示时,您可以使用(例如)

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

    如果要将其存储为圆形,则可以使用

    >> (2.3465*100).round / 100.0
    => 2.35
    
  • 372

    你可以用它来四舍五入..

    //to_f is for float
    
    salary= 2921.9121
    puts salary.to_f.round(2) // to 2 decimal place                   
    
    puts salary.to_f.round() // to 3 decimal place
    

相关问题