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

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

    Use sprintf if you want to print trailing zeros

    2.0.0-p353 :001 > sprintf "%.3f", 500
     => "500.000"
    2.0.0-p353 :002 > sprintf "%.4f", 500
     => "500.0000"
    2.0.0-p353 :003 >
    

提交回复
热议问题