我想将进度的
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
?
使用
.formatted(...)
时,您首先选择要使用的格式样式,在本例中为 FormatStyle.Percent
progress.formatted(.percent)
然后您可以根据自己的喜好配置此格式样式
progress.formatted(.percent.precision(.fractionLength(1)))
另一个带有舍入规则的示例
progress.formatted(.percent.precision(.fractionLength(1)).rounded(rule: .down))