swift - 在 Swift 中四舍五入

标签 swift rounding

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/

相关文章:

macos - Swift NSScriptCommand 执行默认实现

ios - 如何使用 Swift 在 Alamofire 函数中返回 true/false?

java - 意外的 BigDecimal 结果。 1 除以 3 结果为 1。不确定为什么

sql-server - TSQL 对小数进行舍入

ios - 为什么 Swift ARC 不首先中断属性引用以防止保留循环?

ios - 如何在 info.plist 文件 xcode ios 中使用 Code 值

ios - 如何将选中的图片转换为字符串进行存储?

php - 四舍五入机制至最接近的 0.05

javascript - 在 Javascript 中将小数添加到字符串

Android - 四舍五入到小数点后两位