使用 NumberFormatter 从浮点数舍入/截断小数位(Ubuntu 22.04)

问题描述 投票:0回答:1

我需要在逗号后始终有 2 位数字,但某些浮点数的格式无法正确? (如下所示)有什么技巧吗?

代码:

import Foundation
let floatNumber: Float = 17889.055
let roundedNumber: Float = (floatNumber * 100).rounded() / 100
let formatter: NumberFormatter = NumberFormatter()
formatter.locale = Locale(identifier: "de_DE")
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
formatter.groupingSeparator = "."
formatter.decimalSeparator = ","

print(formatter.string(from: NSNumber(value: floatNumber)) ?? String(format: "%.2f", floatNumber)) 
print(formatter.string(from: NSNumber(value: roundedNumber)) ?? String(format: "%.2f", roundedNumber)) 

输出:

swift test.swift 
17.889,055
17.889,061

预计:

swift test.swift 
17.889,06
17.889,06
swift ubuntu rounding foundation numberformatter
1个回答
0
投票

这似乎是 Linux (ubuntu 22.04) 问题;适用于 Macos 14.7; 但还没有找到解决方案;

© www.soinside.com 2019 - 2024. All rights reserved.