开发者

Round up to the nearest tenth?

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 an开发者_JAVA百科y amount past a full tenth, it should be rounded up.

I'm running Ruby 1.8.7.


This works in general:

ceil(number*10)/10

So in Ruby it should be like:

(number*10).ceil/10.0


Ruby's round method can consume precisions:

10.38.round(1) # => 10.4

In this case 1 gets you rounding to the nearest tenth.


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


To round up to the nearest tenth in Ruby you could do

(number/10.0).ceil*10

(12345/10.0).ceil*10 # => 12350


(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜