将 Double 舍入到最接近的 10

Round Double to closest 10

我想将 Double 四舍五入到最接近的 10 的倍数。

例如,如果数字是 8.0,则四舍五入为 10。 如果数字是 2.0,则四舍五入为 0。

我该怎么做?

您可以使用 round() 函数(对浮点数进行舍入 到最接近的整数值)并应用 10 的 "scale factor":

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

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)
}

在Swift3.0中是

10 * Int(round(Double(ratio / 10)))

swift 中 BinaryFloatingPoint 的不错扩展:

extension BinaryFloatingPoint{
    func roundToTens() -> Int{
        return 10 * Int(Darwin.round(self / 10.0))
    }

    func roundToHundreds() -> Int{
        return 100 * Int(Darwin.round(self / 100.0))
    }
}

定义舍入函数为

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

您还可以扩展 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) // 320

四舍五入到任意数字的扩展!

extension Int{
   func rounding(nearest:Float) -> Int{
       return Int(nearest * round(Float(self)/nearest))
    }
}
extension Double {
    var roundToTens: Double {
        let divideByTen = self / 10
        let multiByTen = (ceil(divideByTen) * 10)
        return multiByTen
    }
}

用法: 36. roundToTens