lain
lain

Reputation: 11

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

Upvotes: 1

Views: 75

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51821

I managed to reproduce this using an online playground that was running on linux.

The solution is to not use the numberStyle property and instead define the format manually using the format property. See the format property documentation and the first link on that page for more information on the format syntax

let formatter: NumberFormatter = NumberFormatter()
formatter.locale = Locale(identifier: "de_DE")
formatter.format = "#,##0.00"

Upvotes: 0

Related Questions