如何将十进制数(double)格式化为具有一定精度且基于默认Locale的字符串?

Nic*_*ico 1 swift

到目前为止,我将我的双打格式化为这样的字符串:

String(format:"%0.4f", rate)
Run Code Online (Sandbox Code Playgroud)

问题:小数分隔符总是.在法国,例如我们使用,

然后,我用了一个NSNumberFormatternumberStyle = .DecimalStyle后来为我做之前,我不能选择的4位数字的精度.

我的解决方案是什么?

谢谢

Mar*_*n R 8

使用a NSNumberFormatter并设置要使用的最小和最大 小数位数:

let fmt = NSNumberFormatter()
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let output = fmt.stringFromNumber(123.123456789)!
println(output) // 123,1235 (for the German locale)
Run Code Online (Sandbox Code Playgroud)

Swift 3(及更高版本)的更新:

let fmt = NumberFormatter()
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let output = fmt.string(from: 123.123456789)!
print(output) // 123,1235 (for the German locale)
Run Code Online (Sandbox Code Playgroud)