Round up to the nearest tenth?

懵懂的女人 提交于 2019-12-28 04:18:29

问题


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.


回答1:


This works in general:

ceil(number*10)/10

So in Ruby it should be like:

(number*10).ceil/10.0



回答2:


Ruby's round method can consume precisions:

10.38.round(1) # => 10.4

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




回答3:


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



回答4:


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

(number/10.0).ceil*10

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




回答5:


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



来源:https://stackoverflow.com/questions/7233218/round-up-to-the-nearest-tenth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!