Swift 3 双舍入函数

Swift 3 double rounding func

我在 Swift 中写入 'number prettifier' 时遇到浮点精度问题。我有这个代码:

func prettifyNumber(number:Int) -> String {
    let thousands = Double(number)/1000.0;
    var prettyNumber = String(format: "%.1fk", thousands)
    return prettyNumber 
}

我想要的行为是:

5000 -> "5.0k"

9999 -> “9.9k”

50300 -> “50.3k”

99999 -> “99.9k”

等...

但是,如果我通过 999999,我得到:

999999 -> “1000.0k”

thousands == 999.99900000000002

我知道我可以做一些字符串操作来伪造正确答案,但我想干净地实现它。有什么建议么?

非常感谢!

您可以使用数字格式化程序将最小和最大小数位数设置为 1,并将 roundingMode 设置为向下:

extension Formatter {
    static let kNumber: NumberFormatter = {
       let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.maximumFractionDigits = 1
        formatter.minimumFractionDigits = 1
        formatter.roundingMode = .down
        return formatter
    }()
}

extension Int {
    var kFormatted: String {
        return (Formatter.kNumber.string(for: Double(self).divided(by: 1000) ) ?? "") + "k"
    }
}

5000.kFormatted     // "5.0k"
9999.kFormatted    // "9.9k"
50300.kFormatted   // "50.3k"
99999.kFormatted  // "99.9k"