swift 如何使用指定精度的.formatted(.percent)?(格式样式协议)

6ovsh4lw  于 11个月前  发布在  Swift
关注(0)|答案(1)|浏览(107)

我想将一个从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

czfnxgou

czfnxgou1#

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

progress.formatted(.percent)

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

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

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

progress.formatted(.percent.precision(.fractionLength(1)).rounded(rule: .down))

相关问题