Not surprisingly, it's extremely quicker to convert to a string and
match a regular expression.

      user     system      total        real
spf  :  1.560000   0.000000   1.560000 (  1.557252)
*100 :  0.320000   0.000000   0.320000 (  0.322573)
*.01 :  0.350000   0.000000   0.350000 (  0.343289)
regex:  0.000000   0.000000   0.000000 (  0.000019)

The expression
(^-?\d+(\.\d{1,2})?) matches all the following:

12
1.2
1.234567890
12.34567890
123.4567890
1234.567890
-12
-1.2
-1.234567890
-12.34567890
-123.4567890
-1234.567890

-----

require 'benchmark'

times = 1000000
float = 9.234234765765765764
Benchmark.bm do |r|
  r.report('spf  :') {
    times.times do
      f1 = sprintf('%.2f' ,float).to_f
    end
  }
  r.report('*100 :') {
    times.times do
      f2 = (100 * float).round/100.0
    end
  }
  r.report('*.01 :') {
    times.times do
      f3 = (100 * float).round*0.01
    end
  }
  r.report('regex:') {
    f4 = float.to_s.match(/(^-?\d+(\.\d{1,2})?)/)[1].to_f
  }
end

-- 
Posted via http://www.ruby-forum.com/.