我想将一个从0到1的进度Double
值转换为一个格式良好的String
,其中包含选定数量的小数位,例如:0.789123456至“79.1%”
增加挑战:我想使用新的FormatStyle协议方法. formed()。
令我惊讶的是,我不能让它工作。我找不到一种方法来指定精度。
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
?
1条答案
按热度按时间czfnxgou1#
使用
.formatted(...)
时,首先选择要使用的格式样式,在本例中为FormatStyle.Percent
然后您可以根据自己的喜好配置此格式样式
另一个具有舍入规则的示例