Reputation: 25328
I need to round up to the nearest tenth. What I need is ceil
but with precision to the first decimal place.
Examples:
10.38 would be 10.4
10.31 would be 10.4
10.4 would be 10.4
So if it is any amount past a full tenth, it should be rounded up.
I'm running Ruby 1.8.7.
Upvotes: 12
Views: 14461
Reputation: 4930
(10.33 + 0.05).round(1) # => 10.4
This always rounds up like ceil, is concise, supports precision, and without the goofy /10 *10.0 thing.
Eg. round up to nearest hundredth:
(10.333 + 0.005).round(2) # => 10.34
To nearest thousandth:
(10.3333 + 0.0005).round(3) # => 10.334
etc.
Upvotes: 0
Reputation: 249
To round up to the nearest tenth in Ruby you could do
(number/10.0).ceil*10
(12345/10.0).ceil*10
# => 12350
Upvotes: 2
Reputation: 3595
Ruby's round method can consume precisions:
10.38.round(1) # => 10.4
In this case 1 gets you rounding to the nearest tenth.
Upvotes: 7
Reputation: 1278
If you have ActiveSupport available, it adds a round method:
3.14.round(1) # => 3.1
3.14159.round(3) # => 3.142
The source is as follows:
def round_with_precision(precision = nil)
precision.nil? ? round_without_precision : (self * (10 ** precision)).round / (10 ** precision).to_f
end
Upvotes: 3
Reputation: 655169
This works in general:
ceil(number*10)/10
So in Ruby it should be like:
(number*10).ceil/10.0
Upvotes: 29