James Edward Gray II wrote:

> You're looking for sprintf():
*Slaps hand on head*

I didn't even think about sprintf. I guess I was so fixed on looking for

a way to round numbers in the various Numeric objects that it didn't

occur to me to look in the string functionality.

sprintf() still seems a bit to C-ish for me. I kind of like my round

extension that allows for an optional arg. The question is my

implementation more efficient or using sprintf more efficient? Benchmark

to the rescue:

My implementation through 1 million iterations:

user system total real

No Decimal: 5.410000 0.000000 5.410000 ( 5.413982)

5 Decimal Places: 13.260000 0.000000 13.260000 ( 13.259163)

13 Decimal Places: 21.490000 0.000000 21.490000 ( 21.481821)

Sprintf implementation through 1 million iterations:

user system total real

No Decimal: 12.400000 0.000000 12.400000 ( 12.362547)

5 Decimal Places: 15.310000 0.000000 15.310000 ( 15.549580)

13 Decimal Places: 14.700000 0.020000 14.720000 ( 16.145235)

Looks like my implementation leads for the case where there are less

decimal places remaining (the more common case) and sprintf leads when

there are more. Of course at this point we are really just splitting

hairs.

For reference here are the implementations and benchmark script:

# My implementation

class Float

alias

ldround :round

def round( sd=0 )

return (self * (10 ** sd)).oldround.to_f / (10**sd)

end

end

# Sprintf implementation

class Float

alias

ldround :round

def round( sd=0 )

return ("%.#{sd}f" % self).to_f

end

end

Benchmark script:

#!/usr/bin/ruby

require 'benchmark'

include Benchmark

require 'sprintf_round'

n = 1000000

pi = 3.14159265358979

bm(17) do |test|

test.report('No Decimal:') do

n.times do |x|

pi.round

end

end

test.report('5 Decimal Places:') do

n.times do |x|

pi.round(5)

end

end

test.report('13 Decimal Places:') do

n.times do |x|

pi.round(13)

end

end

end