gpt4 book ai didi

swift - 在 Swift 中四舍五入

转载 作者:可可西里 更新时间:2023-11-01 00:27:47 26 4
gpt4 key购买 nike

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

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.

示例:

  • 2.5 舍入为 2.0
  • 2.6 四舍五入到 3.0
  • 2.4 四舍五入为 2.0

对于负数:

  • -2.5 四舍五入为 -2.0
  • -2.6 四舍五入为 -3.0
  • -2.4 四舍五入为 -2.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

关于swift - 在 Swift 中四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55216963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com