Rounding/truncating decimal places from floats with NumberFormatter (Ubuntu 22.04)

i need 2 digits after the comma consistently but there are certain floats that just wont be formatted correctly? (as seen below) are the tricks around this?

code:

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)) 

output:

swift test.swift 
17.889,055
17.889,061

expected:

swift test.swift 
17.889,06
17.889,06

Update:

this appears to be a linux (ubuntu 22.04) issue; works on macos 14.7; haven’t found a solution for it though;

Output on macOS:

17.889,05
17.889,06
import Foundation

let floatNumber: Float = 17889.055
let roundedNumber: Float = (floatNumber * 100).rounded() / 100

// Format the numbers with 2 decimal places manually
let formattedFloatNumber = String(format: "%.2f", floatNumber)
let formattedRoundedNumber = String(format: "%.2f", roundedNumber)

print(formattedFloatNumber)  // Expected output: 17889,06
print(formattedRoundedNumber)  // Expected output: 17889,06

Explanation:

  • String(format: "%.2f"): This ensures that the float is formatted with exactly two decimal places, regardless of the platform.
  • You can manually replace the decimal separator if needed:
let formattedWithCommas = formattedFloatNumber.replacingOccurrences(of: ".", with: ",")
print(formattedWithCommas)  // Prints the number with a comma as the decimal separator