首页 > 解决方案 > 如何在 Swift 中不四舍五入地打印只有 2 位数字的浮点数?

问题描述

我有一个从 json 服务器响应初始化的浮点数,如 65.788、43.77、89、58.86985……我只需要用两位小数打印它。但没有任何回合。

我的问题是,虽然我将浮点数格式化为仅添加两位数字,但这种格式正在应用最后一位数字的自动轮次。

let weight = 65.788
let string = String(format: "%.2f", weight). // ->  65.79

我得到 65.79 但我需要得到 65.78

怎么能从 json 响应的数量中得到只有两位数而不四舍五入?谢谢!

标签: iosswiftfloating-pointroundingprecision

解决方案


将 NumberFormatter 与.roundingMode = .down

    let nf = NumberFormatter()
    nf.roundingMode = .down

    // max of 2 decimal places (e.g. 1.23, 1.2, 1)
    nf.maximumFractionDigits = 2

    // starting with Strings
    ["65.788", "1.2", "1.9", "1"].forEach { s in
        let n = Float(s)
        let t = nf.string(for: n)
        print("[" + t! + "]")
    }

    // starting with Numbers
    [65.788, 1.2, 1.9, 1].forEach { n in
        let t = nf.string(for: n)
        print("[" + t! + "]")
    }

    // if you want exactly 2 decimal places (e.g. 1.23, 1.20, 1.00)
    nf.minimumFractionDigits = 2

    // starting with Strings
    ["65.788", "1.2", "1.9", "1"].forEach { s in
        let n = Float(s)
        let t = nf.string(for: n)
        print("[" + t! + "]")
    }

    // starting with Numbers
    [65.788, 1.2, 1.9, 1].forEach { n in
        let t = nf.string(for: n)
        print("[" + t! + "]")
    }

输出:

[65.78]
[1.2]
[1.9]
[1]
[65.78]
[1.2]
[1.9]
[1]
[65.78]
[1.20]
[1.90]
[1.00]
[65.78]
[1.20]
[1.90]
[1.00]

显然,您想使用错误检查来确保您的原始字符串可以转换为数字等......


推荐阅读