Prev: How to uninstall ruby on FreeBSD 8.0?
Next: undefined method `call' for nil:NilClass (NoMethodError)
From: Chad Weier on 20 Jul 2010 08:13 I have a method which calculates values and creates and object in a class Acalculation.new(valuea, valueb) they go to def to_s "#{@valuea}#{@valueb}" end If valuea is 100 and valueb is 555555.5555 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. -- Posted via http://www.ruby-forum.com/.
From: Luc Heinrich on 20 Jul 2010 08:48 On 20 juil. 2010, at 14:13, Chad Weier wrote: > valuea - 100.00 valueb - 555,555.56 "valuea - %.2f valueb - %.2f" % [valuea, valueb] This returns "valuea - 100.00 valueb - 555555.56" Extra steps need to be taken for the thousands separator, I don't think Ruby has anything built-in for that. -- Luc Heinrich - luc(a)honk-honk.com
From: Colin Bartlett on 20 Jul 2010 10:31
[Note: parts of this message were removed to make it a legal post.] On Tue, Jul 20, 2010 at 1:13 PM, Chad Weier <emily.ward89(a)gmail.com> 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 |