Joel VanderWerf
3/22/2006 6:32:00 AM
Pat Maddox wrote:
> I'm doing some math that results in floats with ~10 decimal places,
> but I'd like to round them to 2 places. Is there a built in way of
> doing this? Right now I'm doing format("%0.2f", the_float).to_f,
> which seems to work fine but it seems like an ugly way of doing it.
>
> Thanks,
> Pat
>
(the_float*100).round/100.0 is probably a bit faster... you might want
to check the benchmarks, though. Floats are inefficient in ruby, and the
string ops might actually be faster....
Oh what the heck, here's the benchmark, and the winner is... strings!
This might be good place to use a C extension, if you really need it to
be fast.
----
require 'benchmark'
n = 1000000
the_float = 1.0/7
raise unless ("%0.2f" % the_float).to_f == (the_float*100).round/100.0
Benchmark.bmbm(10) do |rpt|
rpt.report("float rounding") do
n.times {
("%0.2f" % the_float).to_f
}
end
rpt.report("string rounding") do
n.times {
(the_float*100).round/100.0
}
end
end
__END__
Output:
Rehearsal ---------------------------------------------------
float rounding 3.220000 0.000000 3.220000 ( 5.749314)
string rounding 2.240000 0.000000 2.240000 ( 4.452959)
------------------------------------------ total: 5.460000sec
user system total real
float rounding 3.170000 0.010000 3.180000 ( 6.379592)
string rounding 2.210000 0.000000 2.210000 ( 4.422063)
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407