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

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

    I don't see anything like that in Float. Float is mostly a wrapper for the native double type and given the usual binary/decimal issues, I'm not that surprised that Float doesn't allow you to manipulate the significant digits.

    However, BigDecimal in the standard library does understand significant digits but again, I don't see anything that allows you to directly alter the significant digits in a BigDecimal: you can ask for it but you can't change it. But, you can kludge around that by using a no-op version of the mult or add methods:

    require 'bigdecimal'
    a = BigDecimal.new('11.2384')
    a.mult(1, 2) # the result is 0.11E2   (i.e. 11)
    a.add(0, 4)  # the result is 0.1124E2 (i.e. 11.24)
    

    The second argument to these methods:

    If specified and less than the number of significant digits of the result, the result is rounded to that number of digits, according to BigDecimal.mode.

    Using BigDecimal will be slower but it might be your only choice if you need fine grained control or if you need to avoid the usual floating point problems.

提交回复
热议问题