ios - 格式双至最大非零有效数字
问题描述
是否有格式说明符将双精度格式设置为仅在小数点后最多包含最大数量的非零有效数字?
例如,如果我想要最多 4 个有效数字并且数字是:
3.14159265359,我要显示3.1459
5.7350,我要 5.735
2.680,我要2.68
9.200,我要 9.2
7.000,我要 7(没有小数点)
解决方案
您可以使用NumberFormatter
. 您只需要设置maximumFractionDigits
to4
和minimumFractionDigits
to 0
:
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.maximumFractionDigits = 4
nf.minimumFractionDigits = 0
nf.string(for: 3.14159265359) // "3.1416"
nf.string(for: 5.7350) // "5.735"
nf.string(for: 2.680) // "2.68"
nf.string(for: 9.200) // "9.2"
nf.string(for: 7.000) // "7"
如果您想对结果进行四舍五入,即3.1415
只需将 NumberFormatter roundingMode 属性设置为.floor
:
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.maximumFractionDigits = 4
nf.minimumFractionDigits = 0
nf.roundingMode = .floor
nf.string(for: 3.14159265359) // "3.1415"
推荐阅读
- javascript - 如何在克隆部分的 HTML 页面上显示来自 DB 的信息?
- python - 以设计格式将函数输出作为另一个函数参数传递
- python - Django 在虚拟环境中的问题
- javascript - JS 参数与参数
- javascript - javascript中的WAP在每个空白处插入新行
- django - 从网站地理封锁用户的最简单方法是什么?
- vb.net - VB.NET 的 FirstOrDefaultDynamic 使用示例
- javascript - ExtJS - 在哪里放置新插件?
- ansible - 集合的 Ansible 角色依赖处理
- java - 如何使用 Java SDK 检查 Azure Cosmos DB 客户端连接是否成功?