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
Some of the previous answers and comments have alluded to this solution but this is what worked for me:
There is probably better way, but this seems to work fine:
Here's an implementation that doesn't use strings or other libraries.
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
oradd
methods:The second argument to these methods:
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.
Use sprintf if you want to print trailing zeros
You are probably looking for Ruby's Decimal.
You could then write:
Or if you prefer to use the same syntax add this as a function to class Float like this:
Usage would then be the same, i.e.
To use it, install the gem