ios - 如何在 Swift 中不四舍五入地打印只有 2 位数字的浮点数?
问题描述
我有一个从 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 响应的数量中得到只有两位数而不四舍五入?谢谢!
解决方案
将 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]
显然,您想使用错误检查来确保您的原始字符串可以转换为数字等......
推荐阅读
- java - 列表
表现为列表 - javascript - svg 中的函数不是通过 html 中的 javascript 调用的
- string - 如何将字符串拆分为六个字符的数组?
- mysql - 这是一对一的例子吗?
- tensorflow - 如何在 Tensorflow Serving 中添加自定义可服务对象
- android - 错误:进程以非零退出值 1 结束
- java - 配置问题:找不到 XML 模式命名空间的 Spring NamespaceHandler [http://www.springframework.org/schema/context]
- python-3.x - 如何使随机选择概率偏向一个选项?
- tensorflow - 在 Google Colaboratory 上运行两次出现 gpu 错误
- alexa - 在我的技能范围内为 Alexa 创造新的声音