我想把Double舍入到最接近10的倍数。
例如,如果数字为8.0,则为10,如果数字为2.0,则为0。
我怎么能这么做?
发布于 2015-01-13 12:48:15
您可以使用round()函数(将浮点数舍入到最近的整数)并应用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除以10 (1.51)、四舍五入(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)
}发布于 2017-08-13 09:55:35
将舍入函数定义为
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更新更通用的定义
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)))
}和使用
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))版画
-13.25 Double
9.0 Double
10 Int发布于 2018-05-31 21:19:32
您还可以扩展FloatingPoint协议并添加一个选项来选择舍入规则:
extension FloatingPoint {
func rounded(to value: Self, roundingRule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Self {
(self / value).rounded(roundingRule) * value
}
}let value = 325.0
value.rounded(to: 10) // 330 (default rounding mode toNearestOrAwayFromZero)
value.rounded(to: 10, roundingRule: .down) // 320https://stackoverflow.com/questions/27922406
复制相似问题