使用 Swift “.formatted()” 删除尾随零的小数?

Wil*_* T. 2 number-formatting swift

我正在尝试从双打中删除尾随零,我看到的代码与此类似

let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
print(formatter.string(from: 1.0000)!) // 1
print(formatter.string(from: 1.2345)!) // 1.23
Run Code Online (Sandbox Code Playgroud)

这需要您创建一个 NumberFormatter()。我知道苹果最近推出了一个新的 .formatted() 函数。有谁知道是否可以使用这个新系统执行上述操作?

该文档对我来说有点复杂,但到目前为止我只看到了设置精度的能力。

let string = 1.00000.formatted(.number.precision(.fractionLength(2)))
// 1.00
Run Code Online (Sandbox Code Playgroud)

Joa*_*son 6

.precision是你应该使用的,然后有一个变体.fractionLength,它接受一个范围作为参数,

\n
10_000.123.formatted(.number.precision(.fractionLength(0\xe2\x80\xa62)))\n
Run Code Online (Sandbox Code Playgroud)\n