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?
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.