在 Swift 中四舍五入

Round Half Down in Swift

Swift 中是否存在与 Java 中的 ROUND_HALF_DOWN 行为相同的舍入模式?

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. Behaves as for RoundingMode.UP if the discarded fraction is > 0.5; otherwise, behaves as for RoundingMode.DOWN.

示例:

对于负数:

是的,您可以使用 NSNumberFormatter 和 RoundingMode

做类似的事情

在这里阅读它们

NSNumberFormatter

RoundingMode

Swift根据Apple

规则实现.round()功能

FloatingPointRoundingRule

case awayFromZero

四舍五入到最接近的允许值,其幅度大于或等于源的幅度。

case down

舍入到小于或等于源的最接近的允许值。

case toNearestOrAwayFromZero

四舍五入到最接近的允许值;如果两个值同样接近,则选择幅度较大的那个。

case toNearestOrEven

四舍五入到最接近的允许值;如果两个值同样接近,则选择偶数。

case towardZero

四舍五入到幅度小于或等于源幅度的最接近的允许值。

case up

舍入到大于或等于源的最接近的允许值。

正如@MohmmadS 所说,这些是内置的舍入方法。

您可以像这样实现自定义舍入:

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

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

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

示例:

round(52.376, toNearest: 0.01) // 52.38
round(52.376, toNearest: 0.1)  // 52.4
round(52.376, toNearest: 0.25) // 52.5
round(52.376, toNearest: 0.5)  // 52.5
round(52.376, toNearest: 1)    // 52
 var a = 6.54
        a.round(.toNearestOrAwayFromZero)
        // a == 7.0

        var b = 6.54
        b.round(.towardZero)
        // b == 6.0


        var c = 6.54
        c.round(.up)
        // c == 7.0


        var d = 6.54
        d.round(.down)
        // d == 6.0

你也可以这样做,但也需要取小数点后的值。

据我所知,没有 FloatingPointRoundingRule 具有与 Java 的 ROUND_HALF_DOWN 相同的行为,但您可以通过组合 rounded()nextDownnextUp:

func roundHalfDown(_ x: Double) -> Double {
    if x >= 0 {
        return x.nextDown.rounded()
    } else {
        return x.nextUp.rounded()
    }
}

示例:

print(roundHalfDown(2.4)) // 2.0
print(roundHalfDown(2.5)) // 2.0
print(roundHalfDown(2.6)) // 3.0

print(roundHalfDown(-2.4)) // -2.0
print(roundHalfDown(-2.5)) // -2.0
print(roundHalfDown(-2.6)) // -3.0

或者作为通用的扩展方法,使其可以与所有浮点类型一起使用(FloatDoubleCGFloat):

extension FloatingPoint {
    func roundedHalfDown() -> Self {
        return self >= 0 ? nextDown.rounded() : nextUp.rounded()
    }
}

示例:

print((2.4).roundedHalfDown()) // 2.0
print((2.5).roundedHalfDown()) // 2.0
print((2.6).roundedHalfDown()) // 3.0

print((-2.4).roundedHalfDown()) // -2.0
print((-2.5).roundedHalfDown()) // -2.0
print((-2.6).roundedHalfDown()) // -3.0