Set Float Accuracy in Ruby

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?

+46
floating-point ruby precision
Dec 19 '09 at 19:49
source share
4 answers

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 .

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.

+57
Aug 6 2018-12-12T00:
source share

You can use sprintf:

 sprintf( "%0.02f", 123.4564564) 
+34
Dec 19 '09 at 19:52
source share

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.

+32
Dec 19 '09 at 10:30
source share

You can use puts

 z = #{'%.3f' % z} 
0
Sep 20 '17 at 12:45
source share



All Articles