Is it possible to set the accuracy of the display 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 need to override the to_s Float method?
to_s
Float
z.round(2) or x.round(3) is the simplest solution. See http://www.ruby-doc.org/core-1.9.3/Float.html#method-i-round .
z.round(2)
x.round(3)
However, this will only guarantee that it is no more than a lot of numbers. In the case of 1/3, this is normal, but if you said 0.25.round(3) , you will get 0.25, not 0.250.
0.25.round(3)
You can use sprintf:
sprintf( "%0.02f", 123.4564564)
Usually I just do the conversion in open source, for example:
puts "%5.2f" % [1.0/3.0]
Ruby calls Kernel # format for such expressions because String has the main% operator defined on it. Think of it as printf for Ruby if that calls you for you.
You can use puts
z = #{'%.3f' % z}