From: Gavin Kistner Date: 2005-09-13T22:39:46+09:00 Subject: Re: Quick question. On Sep 13, 2005, at 7:22 AM, Brian Schr�der wrote: > Or you can use the % operator on a string which I like better. I.e. > "%3.2f" % 1.0 #=> " 1.00" Just remember that if you have multiple formatted pieces in the same string, you need to supply the argument to the #% method as an array: m = 57.23562 s = 83.333333 "%3.2f - %3.2f = %3.2f" % [ m, s, m-s ] #=> "57.24 - 83.33 = -26.10" The fun comes when you use string interpolation along with sprintf's codes: class Numeric def rounded_to( decimals ) decimals = decimals.round if decimals < 0 factor = 10.0 ** -decimals ( ( self / factor ).round * factor ).round.to_s else "%.#{decimals}f" % self end end end [ 1, -1, 0.017, -0.017, 1254, -81.2412234 ].each{ |number| [5,2,1,0,-1,-2,-3].each{ |decimal_places| puts number.rounded_to( decimal_places ) } puts '-' * 40 } 1.00000 1.00 1.0 1 0 0 0 ---------------------------------------- -1.00000 -1.00 -1.0 -1 0 0 0 ---------------------------------------- 0.01700 0.02 0.0 0 0 0 0 ---------------------------------------- -0.01700 -0.02 -0.0 -0 0 0 0 ---------------------------------------- 1254.00000 1254.00 1254.0 1254 1250 1300 1000 ---------------------------------------- -81.24122 -81.24 -81.2 -81 -80 -100 0 ----------------------------------------