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

前端 未结 7 1432
孤城傲影
孤城傲影 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:12

    Here's an implementation that doesn't use strings or other libraries.

    class Float
      def signif(digits)
        return 0 if self.zero?
        self.round(-(Math.log10(self).ceil - digits))
      end
    end
    
    0 讨论(0)
提交回复
热议问题