在斯威夫特的一半下来

问题描述 投票:2回答:5

Swift中的舍入模式是否与Java中的ROUND_HALF_DOWN相同?

舍入模式向“最近邻居”舍入,除非两个邻居等距,在这种情况下向下舍入。如果丢弃的分数> 0.5,则表现为RoundingMode.UP;否则,表现为RoundingMode.DOWN。

例:

  • 2.5轮到2.0
  • 2.6轮到3.0
  • 2.4轮到2.0

对于负数:

  • -2.5轮到-2.0
  • -2.6向下舍入到-3.0
  • -2.4轮到-2.0
swift rounding
5个回答
4
投票

有 - 据我所知 - 没有与Java的FloatingPointRoundingRule具有相同行为的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

1
投票

根据.round(),Swift用规则实现Apple函数

FloatingPointRoundingRule

case awayFromZero

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

case down

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

case toNearestOrAwayFromZero

舍入到最接近的允许值;如果两个值相等,则选择幅度更大的值。

case toNearestOrEven

舍入到最接近的允许值;如果两个值相等,则选择偶数。

case towardZero

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

case up

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


0
投票

是的,你可以使用NSNumberFormatter和RoundingMode做类似的事情

在这里阅读它们

NSNumberFormatter

RoundingMode


0
投票
 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

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


0
投票

正如@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
© www.soinside.com 2019 - 2024. All rights reserved.