如何使用指定精度的.formatted(.percent)? (FormatStyle协议)

问题描述 投票:0回答:1

我想将进度的

Double
值范围从 0 到 1 转换为具有选定数量的小数位数的格式化
String
,例如0.789123456 至“79,1 %”。

新增挑战:我想使用基金会的新

FormatStyle
协议方法
.formatted()

令我惊讶的是,我无法让它工作。我找不到方法来指定精度
这是我的一些尝试:

var progress: Double = 0.789123456
progress.formatted(.percent) // "78,9123456 %" it starts so easy
progress.formatted(.number.precision(.fractionLength(1))) // "0,79"
progress.formatted(.number.precision(.fractionLength(0...1))) // "0,79"
progress.formatted(.number.precision(.fractionLength(0...1))).formatted(.percent) // does not compile
// "Instance method 'formatted' requires the types 'FloatingPointFormatStyle<Double>.FormatOutput' (aka 'String') and 'FloatingPointFormatStyle<Double>.Percent.FormatInput' (aka 'Double') be equivalent"

Double(progress.formatted(.number.precision(.fractionLength(1)))) // nil
Double("0.79")?.formatted(.percent) // "79 %", gotcha, I have german Locale!

Locale.current // "en_DE (current)"
Locale.current.decimalSeparator // ","

Double(progress.formatted(.number.precision(.fractionLength(1))).replacingOccurrences(of: Locale.current.decimalSeparator!, with: ".")) // "0,8"
Double(progress.formatted(.number.precision(.fractionLength(1))).replacingOccurrences(of: Locale.current.decimalSeparator!, with: "."))?.formatted(.percent) // "80 %"

有没有办法用

FormatStyle
做到这一点?
或者我必须选择旧的
NumberFormatter
及其
maximumFractionDigits

swift formatting format
1个回答
3
投票

使用

.formatted(...)
时,您首先选择要使用的格式样式,在本例中为
FormatStyle.Percent

progress.formatted(.percent)

然后您可以根据自己的喜好配置此格式样式

progress.formatted(.percent.precision(.fractionLength(1)))

另一个带有舍入规则的示例

progress.formatted(.percent.precision(.fractionLength(1)).rounded(rule: .down))
© www.soinside.com 2019 - 2024. All rights reserved.