Numberformatter without rounding. One behaviour in Xcode project another in playground

312 views Asked by At

I am experiencing some weird behaviour using the NumberFormatter.

The following code:

let str = "5.99"
let doub = Double(str)
let nsnum = NSNumber(floatLiteral: doub!)
let formatter = NumberFormatter()

formatter.numberStyle = .currency
formatter.locale = NSLocale(localeIdentifier: "da_DK") as Locale!
formatter.currencySymbol = ""

let forStr = formatter.string(from: nsnum)

does not return the same result when run in my Xcode project and when run in a playground.swift file.

In the playground forStr is "5.99" in the project forStr is "6". The behaviour from the playground is the one I'm after.

I have tried adding:

formatter.maximumFractionDigits = 2
formatter.roundingMode = .down

but they have no effect in my project.

Any ideas as of why this is happening?

1

There are 1 answers

1
Anil On

You need to use the round function for this.

Say you need two digits precision. Then you need to multiply by 100, then round it, and then divide the result with 100.

let a = 5.9999
let b = Double(round(100*a)/100)
print(b)  //Output will be 6.0