## 5.3. Rounding Floating Point Values
If you want to round a floating point value to an integer, the method pi = 3.14159 new_pi = pi.round # 3 temp = -47.6 temp2 = temp.round # -48 Sometimes we want to round not to an integer but to a specific number of decimal places. In this case, we could use pi = 3.1415926535 pi6 = eval(sprintf("%8.6f",pi)) # 3.141593 pi5 = eval(sprintf("%8.5f",pi)) # 3.14159 pi4 = eval(sprintf("%8.4f",pi)) # 3.1416 Of course, this is somewhat ugly. Let's encapsulate this behavior in a method that we'll add to class Float def roundf(places) temp = self.to_s.length sprintf("%#{temp}.#{places}f",self).to_f end end Occasionally we follow a different rule in rounding to integers. The tradition of rounding class Float def round2 whole = self.floor fraction = self - whole if fraction == 0.5 if (whole % 2) == 0 whole else whole+1 end else self.round end end end a = (33.4).round2 # 33 b = (33.5).round2 # 34 c = (33.6).round2 # 34 d = (34.4).round2 # 34 e = (34.5).round2 # 34 f = (34.6).round2 # 35 Obviously Now, what if we wanted to round to a number of decimal places, but we wanted to use the "even rounding" method? In this case, we could add a method called class Float # round2 definition as before def roundf2(places) shift = 10**places (self * shift).round2 / shift.to_f end end a = 6.125 b = 6.135 x = a.roundf2(a) # 6.12 y = b.roundf2(b) # 6.13 The preceding code ( |

The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)

ISBN: 0672328844

EAN: 2147483647

EAN: 2147483647

Year: 2004

Pages: 269

Pages: 269

Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net