Convert string to NSDecimalNumber

I am trying to convert String to NSDecimalNumber, here is my code:

class func stringToDecimal (dataToDecimal: String) -> NSDecimalNumber { let dataToDecimal = dataToDecimal.stringByReplacingOccurrencesOfString(",", withString: ".") print(dataToDecimal) let decimalReturn = NSDecimalNumber(string: dataToDecimal) print(decimalReturn) if decimalReturn == NSDecimalNumber.notANumber(){ return 0.00 } return decimalReturn } 

At first I thought that maybe this is wrong, but even with. he does not work. The first print (before conversion) shows, for example, 80.00, but the print (decimalReturn) shows only 80

the if line is just to check if the result is not a number.

+10
source share
3 answers

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 = "," 
+17
source

There is nothing wrong with how you create NSDecimalNumber from String . However, you may not need to worry about replacing the comma for a period, if that is how your local formats are.

The reason it prints 80 instead of 80.00 or 80.00 is because print simply uses the description property for the number. If you want to configure formatting, you must configure 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 
+2
source

When the server calls a specific locale, use it instead of Locale.current. so you don’t want a breakdown depending on user settings

 extension String { var decimalFromServerString: NSDecimalNumber? { let parsed = NSDecimalNumber(string: self, locale: ru_ru_posix) if parsed == .notANumber { return nil } return parsed } } 

PS. if for some reason you are binding the language rigidly to en_US POSIX, then the line "..." goes as 0. Go through the picture:

0
source

All Articles