首页 > 解决方案 > 格式双至最大非零有效数字

问题描述

是否有格式说明符将双精度格式设置为仅在小数点后最多包含最大数量的非零有效数字?

例如,如果我想要最多 4 个有效数字并且数字是:

3.14159265359,我要显示3.1459

5.7350,我要 5.735

2.680,我要2.68

9.200,我要 9.2

7.000,我要 7(没有小数点)

标签: iosswiftformatting

解决方案


您可以使用NumberFormatter. 您只需要设置maximumFractionDigitsto4minimumFractionDigitsto 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"

推荐阅读