From: Colin Bartlett Date: 2010-07-20T23:31:00+09:00 Subject: Re: How do I format return this value? --001485f5afa894803c048bd28834 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jul 20, 2010 at 1:13 PM, Chad Weier wrote: > ... What would be the neatest and cleanest way to convert them to a > formatted value like this (note the rounding also) > valuea - 100.00 valueb - 555,555.56 > I've found lots of code that does bit and pieces like I need but not > anything that does commas and rounding to 2 decimal places. The following methods (for Integers and Floats) are cut down versions of some more general number formatting methods I wrote for myself some time ago. No guarantees that they do what you want, but some quick tests seem to show they do. class Integer # Puts digit separators for each group of 3 digits, # with option to use a separator which is not an underscore. def to_s!( grp_sep = '_' ) s = self.to_s if grp_sep then n = s.length ne = ( if self < 0 then 1 else 0 end ) while (n -= 3) > ne do; s[ n, 0 ] = grp_sep; end end s end end class Float # Puts integer part digit separators for each group of 3 digits, # with option to use a separator which is not an underscore. # (if "." is used as the digits separator then the "decimal separator" # will be changed from "." to ","); def to_s!( n_dec_places, grp_sep = '_' ) unless n_dec_places.kind_of?( Integer ) then raise "Float#to_s! - number of decimal places must be an integer" end unless n_dec_places >= 0 then raise "Float#to_s! - negative number of decimal places yet to be implemented to give robust results" end fmt_str = "%.#{n_dec_places}f" s = sprintf( fmt_str, self ) if grp_sep then n = s.rindex( '.' ) # if n_dec_places == 0 then n = nil s[n, 1] = ',' if n && grp_sep == '.' n ||= s.length ne = ( if self < 0 then 1 else 0 end ) while (n -= 3) > ne do; s[ n, 0 ] = grp_sep; end end s end end --001485f5afa894803c048bd28834--