Rounding a float to the nearest integer in ruby
Try Float.round
.
irb(main):001:0> 5.44.round
=> 5
irb(main):002:0> 5.54.round
=> 6
Round a ruby float up or down to the nearest 0.05
Check this link out, I think it's what you need.
Ruby rounding
class Float
def round_to(x)
(self * 10**x).round.to_f / 10**x
end
def ceil_to(x)
(self * 10**x).ceil.to_f / 10**x
end
def floor_to(x)
(self * 10**x).floor.to_f / 10**x
end
end
Ruby: Rounding float in Ruby
When displaying, you can use (for example)
>> '%.2f' % 2.3465
=> "2.35"
If you want to store it rounded, you can use
>> (2.3465*100).round / 100.0
=> 2.35
Ruby round float to_int if whole number
This is the solution that ended up working the way I want it to:
class Float
alias_method(:original_to_s, :to_s) unless method_defined?(:original_to_s)
def is_whole?
self % 1 == 0
end
def to_s
self.is_whole? ? self.to_i.to_s : self.original_to_s
end
end
This way I can update the is_whole?
logic (I seems like tadman's is the most sophisticated) if needed, and it ensures that anywhere a Float outputs to a string (eg, in a form) it appears the way I want it to (ie, no zeros on the end).
Thanks to everybody for your ideas - they really helped.
How to round a number to the nearest 9 in Ruby
Unfortunately, the round() methods for float don't have much syntactic sugar for rounding to other than the nearest integer. One can build one's own methods—
This method assumes all the numbers are positive. For readability, I advise you wrap this convoluted numerical calculation into a method whose name refers to what it's doing.
def round_to_nearest_9(num)
((num + 1) / 10).round * 10 - 1
end
If you don't want to assume the input number is positive:
def round_to_nearest_9(num)
if num < 0
return ((num - 1) / 10).round * 10 + 1
else
return ((num + 1) / 10).round * 10 - 1
end
end
Ruby round Float up or down to specific decimal significant figure
In Ruby 2.4+, the Float#float
& Float#ceil
methods take a ndigits
argument:
1.33333333.ceil(2) -> 1.34
1.33333333.floor(3) -> 1.333
However, check out this behavior with those STD lib methods:
# In Ruby 2.4.2:
0.07.ceil(2) -> 0.08
1.1.ceil(2) -> 1.11
Not OK in my book.
For older Ruby versions or if you want to get better results than the STB lib gives, you will need to write your own methods. There are a few different blog posts out there, and I'll explain why they're not consistently correct later, but here are some methods that should work correctly every time:
require 'bigdecimal'
class Float
def ceil2(exp = 0)
BigDecimal(self.to_s).ceil(exp).to_f
end
def floor2(exp = 0)
BigDecimal(self.to_s).floor(exp).to_f
end
end
Now for more on why the following are incorrect:
def ceil_to(x)
(self * 10**x).ceil.to_f / 10**x
end
def floor_to(x)
(self * 10**x).floor.to_f / 10**x
end
# These methods also produce bad results for the examples shown above
0.07.ceil(2) -> 0.08
1.1.ceil(2) -> 1.11
I won't go into the details about what is happening (you can find that
here or here), but floating point arithmetic can be messy and rounding errors do occur.
Round to closest integer or closest .5 in Ruby
Multiply by 2, round, divide by 2.
[4.12, 4.24, 4.25, 4.33, 4.53, 4.65, 4.75, 4.84].map do |x|
r = (x * 2).round / 2.0
r.to_i == r ? r.to_i : r
end
=> [4, 4, 4.5, 4.5, 4.5, 4.5, 5, 5]
A way to round Floats down
Based on answer from @kimmmo this should be a little more efficient:
class Float
def round_down n=0
s = self.to_s
l = s.index('.') + 1 + n
s.length <= l ? self : s[0,l].to_f
end
end
1.9991.round_down(3)
=> 1.999
1.9991.round_down(2)
=> 1.99
1.9991.round_down(0)
=> 1.0
1.9991.round_down(5)
=> 1.9991
or based on answer from @steenslag, probably yet more efficient as there is no string conversion:
class Float
def round_down n=0
n < 1 ? self.to_i.to_f : (self - 0.5 / 10**n).round(n)
end
end
Ruby Always Round Up
The problem is that you're currently calling ceil
on 30.to_f
. Here's how Ruby evaluates it:
(67)/(30.to_f.ceil)
# .ceil turns the float into an integer again
(67)/(30.0.ceil)
# and now it's just an integer division, which will be 2
67/30 # = 2
To solve this, you can just add parenthesis:
puts (67/30.to_f).ceil # = 3
Related Topics
Working with a Large Data Object Between Ruby Processes
Accessing Headers from Sinatra
Sass: Dealing with The Ie 4095 Selectors Per Stylesheet Restriction
Rails Sitemap_Generator Uninitialized Constant
How to Host a Rails Web Application
Is There an Easy-To-Use Ftp Library for Ruby
What the Purpose of Bind/Unbind Methods in Ruby
"Ruby.Exe Is Not Recognized as an Internal or External Command" in Windows 7
Date Range Facets with Sunspot in Ruby on Rails
Running a Shell Command from Ruby: Capturing the Output While Displaying the Output
What Ide/Editor Do You Use for Ruby on Linux
Ruby Metaprogramming, How Does Rspec's 'Should' Work
How to Make a Custom Environment in Rails a Default Environment
Good Resources to Learn MACruby
How to Create a Folder (If Not Present) with Logger.New
Failing to Bundle Install Tiny_Tds on MAC Os X 10.8 with Homebrew Freetds