【问题标题】:Rounding a double value (1.005) to (1.01) [duplicate]将双精度值 (1.005) 舍入到 (1.01) [重复]
【发布时间】:2021-07-13 16:41:49
【问题描述】:

在 swift 中舍入数字 1.005 的问题

将 1.005 舍入到小数点后两位的结果是 1.0 而不是 1.01 如何解决?

for i in 1..<11 {
    let value = Double(i) + 0.005
    let roundedValue = round(value * 100) / 100.0
    print(value, roundedValue)
}

输出:

1.005  -> 1.0
2.005  -> 2.01
3.005  -> 3.01
4.005  -> 4.01
5.005  -> 5.01
6.005  -> 6.01
7.005  -> 7.01
8.005  -> 8.01
9.005  -> 9.01
10.005  -> 10.01

【问题讨论】:

  • 使用 String(format: ) 并将字符串转换回 Double。

标签: ios swift double rounding


【解决方案1】:

只需使用NumberFormatter 并将roundingMode 设置为halfUp

extension Formatter {
    static let number: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.minimumFractionDigits = 2
        formatter.maximumFractionDigits = 2
        formatter.roundingMode = .halfUp
        return formatter
    }()
}

Formatter.number.string(for: 1.005)   // "1.01"
Formatter.number.string(for: 2.005)   // "1.01"
Formatter.number.string(for: 3.005)   // "1.01"
Formatter.number.string(for: 4.005)   // "1.01"
Formatter.number.string(for: 5.005)   // "1.01"
Formatter.number.string(for: 6.005)   // "1.01"
Formatter.number.string(for: 7.005)   // "1.01"
Formatter.number.string(for: 8.005)   // "1.01"
Formatter.number.string(for: 9.005)   // "1.01"
Formatter.number.string(for: 10.005)  // "1.01"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多