如何在点后用两位数打印Double并隐藏它们(如果为零)?

时间:2018-10-01 13:11:36

标签: swift

如何在点后用两位数字打印Double并隐藏是否为零?

  • 5.12345-> 5.12

  • 5.00000-> 5

  • 5.10000-> 5.10

1 个答案:

答案 0 :(得分:1)

您可以尝试

func format(_ x: Double) -> String {
    if Double(Int(x)) == x {
        return String(Int(x))
    } else {
        let numberFormatter = NumberFormatter()
        numberFormatter.maximumFractionDigits = 2
        numberFormatter.minimumFractionDigits = 2
        guard let s = numberFormatter.string(for: x) else {
            fatalError("Couldn't format number")
        }
        return s
    }
}

format(5.12)  //"5.12"
format(5.0)   //"5"
format(5.10)  //"5.10"