Use NSNumberFormatter to analyze your input. Set the generatesDecimalNumbers property to true:
let formatter = NumberFormatter() formatter.generatesDecimalNumbers = true
This is how you use it if you want to return 0 when the string cannot 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 for the device locale setting to determine the decimal marker. You must leave it that way. For example, I will force it into the French language:
// 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 use a comma as a decimal mark, you can set the decimalSeparator property:
formatter.decimalSeparator = ","
source share