首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 > Round Double最接近10?

Round Double最接近10?
EN

Stack Overflow用户
提问于 2018-06-01 05:00:29
回答 2查看 0关注 0票数 0

我想将Double放到最接近的10。

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

EN

回答 2

Stack Overflow用户

发布于 2018-06-01 13:51:40

将舍入函数定义为

import Foundation

func round(_ value: Double, toNearest: Double) -> Double {
    return round(value / toNearest) * toNearest
}

为你提供更一般和灵活的方式

let r0 = round(1.27, toNearest: 0.25)   // 1.25
let r1 = round(325, toNearest: 10)      // 330.0
let r3 = round(.pi, toNearest: 0.0001)  // 3.1416
票数 0
EN

Stack Overflow用户

发布于 2018-06-01 14:26:26

可以使用round()函数(将浮点数舍入到最接近的整数值):

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

用法示例:

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

在第二个例子中,15.1除以10(1.51),rounded(2.0),转换为整数(2)并再乘以10(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)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档