How do I round a float to a specified number of si

2020-03-17 14:12发布

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

7条回答
Anthone
2楼-- · 2020-03-17 15:06

@Blou91's answer is nearly there, but it returns a string, instead of a float. This below works for me:

(sprintf "%.2f", 1.23456).to_f

So as a function,

def round(val, sig_figs)
  (sprintf "%.#{sig_figs}f", val).to_f
end
查看更多
登录 后发表回答