我有一个从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响应数中仅取两位而不取整?谢谢!
答案 0 :(得分:4)
将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]
很显然,您想使用错误检查来确保将原始字符串 转换为数字,等等。
答案 1 :(得分:0)
我喜欢单行解决方案,这里有一个
let weight = 12.99999
let string = "\(Double(floor(weight * 100)/100))"
print(string) // 12.99