如何在 Swift 中不四舍五入的情况下打印只有 2 位数字的浮点数?

use*_*888 0 floating-point precision rounding ios swift

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

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

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

我得到 65.79 但我需要得到 65.78

如何从 json 响应的数量中获得只有两位数而不四舍五入的数字?谢谢!

Don*_*Mag 9

使用 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! + "]")
    }
Run Code Online (Sandbox Code Playgroud)

输出:

[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]
Run Code Online (Sandbox Code Playgroud)

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