Besfort Abazi
Besfort Abazi

Reputation: 383

Convert NSString to double - Objective-C

I am confused about converting a NSString to a double, sometimes it works, sometimes it doesn't.

//eg: NSString *string = @"0,50"

a)

double d = [string doubleValue];
// -> d is 0.00

b)

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:2];
NSNumber *num = [formatter numberFromString:string];
double d = [num doubleValue];
// -> d is <null>

What else can I try? Why does it work sometimes?

Thank you in advance!

Upvotes: 0

Views: 1393

Answers (2)

Ashley Mills
Ashley Mills

Reputation: 53101

Decimal numbers can use either a , or . as the decimal separator, depending on the locale. You need to make sure the formatter's locale matches the format of the string you're converting.

This example is in Swift, but the idea is the same…

let formatter = NumberFormatter()
let string1 = "1.3"
formatter.locale = Locale(identifier: "en_GB")
formatter.number(from: string1)
// returns 1.3 (as UK uses '.' for decimal)

let string2 = "1,3"
formatter.number(from: string2)
// returns nil (as formatter doesn't recognise the ','

formatter.locale = Locale(identifier: "fr_FR")
formatter.number(from: string2)
// returns 1.3 (as France uses '.' for decimal)

Alternatively, you can set the decimalSeparator yourself

formatter.decimalSeparator = ","

Upvotes: 2

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36391

In NSNumberFormatterDecimalStyle ,(comma) is used to separate groups of digits (thousands, millions, etc) not for the decimal point. This is much more a matter of locale. Use a locale for which it is the standard decimal point.

---EDIT---

A locale is a language setting of a given environment and is used to present many values as strings (or the converse). So try to use a locale that uses , as the decimal point (for example frfor French). NSNumberFormatter have a property named locale to modify the conversion strategy.

Upvotes: 3

Related Questions