views:

752

answers:

2

Is it possible to set the display precision of a float in Ruby?

Something like:

z = 1/3
z.to_s    #=> 0.33333333333333
z.to_s(3) #=> 0.333
z.to_s(5) #=> 0.33333

Or do I have to override the to_s method of Float?

+5  A: 

You can use sprintf:

sprintf( "%0.02f", 123.4564564)
Andreas Bonini
+5  A: 

I would normally just do the conversion in code, something like:

puts "%5.2f" % [1.0/3.0]
DigitalRoss