Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
>> (3.333).signif(2)
3.3
>> (4.4).signif(3)
4.4 # It's usually 4.40 but that's OK. R does not print the trailing 0's
    # because it returns the float data type. For Ruby we want the same.
>> (5.55).signif(2)
5.6
like image 297
Aleksandr Levchuk Avatar asked Dec 05 '11 08:12

Aleksandr Levchuk


1 Answers

There is probably better way, but this seems to work fine:

class Float
  def signif(signs)
    Float("%.#{signs}g" % self)
  end
end

(1.123).signif(2)                    # => 1.1
(11.23).signif(2)                    # => 11.0
(11.23).signif(1)                    # => 10.0
like image 55
Victor Deryagin Avatar answered Sep 29 '22 20:09

Victor Deryagin