Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
ruby rounding?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="james.d.masters, post: 4556247"] You could always create your own :). Here is a something that I put together. There may be a better method. The weird thing in the code with comparing the remainder to 1e-9 is to deal with floating point precision issues. This may or may not be appropriate... I'm not a rounding expert but it's worked in applications that I developed. Anyway, here it is: class Numeric def even_round() if ((self.truncate % 2 == 0) and ((self.remainder(1).abs - 0.5).abs < 1e-9)) # integer portion is even and on 0.5 threshold self.truncate else # integer portion is odd or not on 0.5 threshold self.round end end end irb(main):012:0> a = [-5.0, -4.5, -4.0, -3.5, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5] => [-5.0, -4.5, -4.0, -3.5, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5] irb(main):013:0> a.map {|e| e.even_round} => [-5, -4, -4, -4, -3, -2, -2, -2, -1, 0, 0, 0, 1, 2, 2, 2, 3, 4, 4, 4] [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
ruby rounding?
Top