首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >双圆至最近10

双圆至最近10
EN

Stack Overflow用户
提问于 2015-01-13 12:39:12
回答 6查看 14K关注 0票数 19

我想把Double舍入到最接近10的倍数。

例如,如果数字为8.0,则为10,如果数字为2.0,则为0。

我怎么能这么做?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2015-01-13 12:48:15

您可以使用round()函数(将浮点数舍入到最近的整数)并应用10的“比例因子”:

代码语言:javascript
复制
func roundToTens(x : Double) -> Int {
    return 10 * Int(round(x / 10.0))
}

示例用法:

代码语言:javascript
复制
print(roundToTens(4.9))  // 0
print(roundToTens(15.1)) // 20

在第二个示例中,15.1除以10 (1.51)、四舍五入(2.0)、转换为整数(2),再乘以10 (20)。

Swift 3:

代码语言:javascript
复制
func roundToTens(_ x : Double) -> Int {
    return 10 * Int((x / 10.0).rounded())
}

另一种选择是:

代码语言:javascript
复制
func roundToTens(_ x : Double) -> Int {
    return 10 * lrint(x / 10.0)
}
票数 46
EN

Stack Overflow用户

发布于 2017-08-13 09:55:35

将舍入函数定义为

代码语言:javascript
复制
import Foundation

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

为您提供了更通用、更灵活的方法来实现它。

代码语言:javascript
复制
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

更新更通用的定义

代码语言:javascript
复制
func round<T:BinaryFloatingPoint>(_ value:T, toNearest:T) -> T {
    return round(value / toNearest) * toNearest
}
func round<T:BinaryInteger>(_ value:T, toNearest:T) -> T {
    return T(round(Double(value), toNearest:Double(toNearest)))
}

和使用

代码语言:javascript
复制
let A = round(-13.16, toNearest: 0.25)
let B = round(8, toNearest: 3.0)
let C = round(8, toNearest: 5)

print(A, type(of: A))
print(B, type(of: B))
print(C, type(of: C))

版画

代码语言:javascript
复制
-13.25 Double
9.0 Double
10 Int
票数 28
EN

Stack Overflow用户

发布于 2018-05-31 21:19:32

您还可以扩展FloatingPoint协议并添加一个选项来选择舍入规则:

代码语言:javascript
复制
extension FloatingPoint {
    func rounded(to value: Self, roundingRule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Self {
       (self / value).rounded(roundingRule) * value
    }
}

代码语言:javascript
复制
let value = 325.0
value.rounded(to: 10) // 330 (default rounding mode toNearestOrAwayFromZero)
value.rounded(to: 10, roundingRule: .down) // 320
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27922406

复制
相关文章

相似问题

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