How do I round a float to a specified number of significant digits in Ruby?

前端 未结 7 1430
孤城傲影
孤城傲影 2021-01-12 03:37

It would be nice to have an equivalent of R\'s signif function in Ruby.

For example:

>> (11.11).signif(1)
10
>> (22.22).signif(2)
22
>         


        
7条回答
  •  礼貌的吻别
    2021-01-12 04:08

    You are probably looking for Ruby's Decimal.

    You could then write:

    require 'decimal/shortcut'
    num = 1.23541764
    D.context.precision = 2
    num_with_2_significant_digits = +D(num.to_s) #  => Decimal('1.2')
    num_with_2_significant_digits.to_f #  => 1.2000000000000002
    

    Or if you prefer to use the same syntax add this as a function to class Float like this:

    class Float
      def signif num_digits
        require 'decimal/shortcut'
        D.context.precision = num_digits
        (+D(self.to_s)).to_f
      end
    end
    

    Usage would then be the same, i.e.

     (1.23333).signif 3
     # => 1.23
    

    To use it, install the gem

    gem install ruby-decimal
    

提交回复
热议问题