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/.
"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.
···
On 20 juil. 2010, at 14:13, Chad Weier wrote:
valuea - 100.00 valueb - 555,555.56
--
Luc Heinrich - luc@honk-honk.com
...
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
···
On Tue, Jul 20, 2010 at 1:13 PM, Chad Weier <emily.ward89@gmail.com> wrote: