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

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

    @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
    

提交回复
热议问题