Convert String to NSDecimalNumber
Use an NSNumberFormatter
to parse your input. Set its generatesDecimalNumbers
property to true:
let formatter = NumberFormatter()
formatter.generatesDecimalNumbers = true
Here's how you use it, if you want to return 0 when the string can't be parsed:
func decimal(with string: String) -> NSDecimalNumber {
return formatter.number(from: string) as? NSDecimalNumber ?? 0
}
decimal(with: "80.00")
// Result: 80 as an NSDecimalNumber
By default, the formatter will look at the device's locale setting to determine the decimal marker. You should leave it that way. For the sake of example, I'll force it to a French locale:
// DON'T DO THIS. Just an example of behavior in a French locale.
formatter.locale = Locale(identifier: "fr-FR")
decimal(with: "80,00")
// Result: 80
decimal(with: "80.00")
// Result: 0
If you really want to always use a comma as the decimal mark, you can set the decimalSeparator
property:
formatter.decimalSeparator = ","
There is nothing wrong with the way you are creating a NSDecimalNumber
from a String
. However, you might not need to worry about replacing the comma with a period if that is how your local formats numbers.
The reason it prints 80 instead of 80,00 or 80.00 is that print
just uses the description
property of the number. If you want to customize the formatting, you should setup your own NSNumberFormatter
.
let number = NSDecimalNumber(string: "80.00")
print(number) // 80
let formatter = NSNumberFormatter()
formatter.minimumFractionDigits = 2
let string = formatter.stringFromNumber(number)
print(string) // 80.0