斯威夫特3双舍入功能

时间:2017-05-15 00:24:02

标签: swift floating-point floating-accuracy

我有一个浮点精度问题,编写了一个数字修饰符'在斯威夫特。我有这段代码:

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 个答案:

答案 0 :(得分:2)

您可以使用数字格式化程序将最小和最大小数位数设置为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"