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

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

    Some of the previous answers and comments have alluded to this solution but this is what worked for me:

    # takes in a float value and returns another float value rounded to 
    # given significant figures.    
    def round_to_sig_figs(val, sig_figs)
      BigDecimal.new(val, sig_figs).to_f
    end
    

提交回复
热议问题