Is NumberFormatter not ready for use in Linux?

The following code will give difference results with macOS and Linux.

let formatter = NumberFormatter()
formatter.negativeFormat = "#.#########"
formatter.positiveFormat = "#.#########"

var a = 0.5

print(formatter.string(from: NSNumber(value: a)))

Can you share the results and versions? Also looks like a bug repot?

1 Like

I got follow results

macOS, swift 5
output: 0.5

Docker swift:4.1
output: 0

Docker vapor/swift:5.0
output: 0

I don’t know is it a bug. The status page of Foundation lib just say NumberFormatter is “Mostly Complete”. I put my code on server and found that the formatter round all the NSNumber to integer.

From the implementation at NumberFormatter.swift is seems that the negativeFormat and positiveFormat are not actually implemented. They set private properties which are otherwise unused. Therefore your formatter behaves (on non-Apple platforms) as if no number format was set at all.

You probably have to control the output format with other properties, for example:

let formatter = NumberFormatter()
formatter.minimumFractionDigits = 4
var a = 0.5
print(formatter.string(from: NSNumber(value: a)))
// Optional("0.5000")

I have workaround by converting Double to Decimal and print Decimal out. This works perfectly.

If you don’t mind, filing a bug at https://bugs.swift.org would be much appreciated

1 Like

Yes, of course.

https://bugs.swift.org/browse/SR-10245

2 Likes

Awesome, thanks :+1:

Terms of Service

Privacy Policy

Cookie Policy