双倍到最接近的 10 [英] Round Double to closest 10

查看:25
本文介绍了双倍到最接近的 10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Double 舍入到最接近的 10 倍数.

I would like to round a Double to the closest multiple of 10.

例如,如果数字是 8.0,则四舍五入到 10.如果数字是 2.0,则将其四舍五入为 0.

For example if the number is 8.0 then round to 10. If the number is 2.0 round it to 0.

我该怎么做?

推荐答案

您可以使用 round() 函数(它对浮点数进行四舍五入到最接近的整数值)并应用 10 的比例因子":

You can use the round() function (which rounds a floating point number to the nearest integral value) and apply a "scale factor" of 10:

func roundToTens(x : Double) -> Int {
    return 10 * Int(round(x / 10.0))
}

示例用法:

print(roundToTens(4.9))  // 0
print(roundToTens(15.1)) // 20

在第二个例子中,15.1 除以十 (1.51),四舍五入 (2.0),转换为整数 (2) 并再次乘以 10 (20).

In the second example, 15.1 is divided by ten (1.51), rounded (2.0), converted to an integer (2) and multiplied by 10 again (20).

Swift 3:

func roundToTens(_ x : Double) -> Int {
    return 10 * Int((x / 10.0).rounded())
}

或者:

func roundToTens(_ x : Double) -> Int {
    return 10 * lrint(x / 10.0)
}

这篇关于双倍到最接近的 10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆