ZeeroCool77
ZeeroCool77

Reputation: 191

How to localise the numbers in iOS?

I did following to localise the strings. I wrote the following in .strings file:

"Hello"="Hello";

and in french , .strings file:

 "Hello"="bonjour";

and I change the label as :

  self.myLabel.text = NSLocalizedString(@"Hello", nil);

I am succesfull upto here. I have two cases:

Consider the number 2.5, where in english system it is 2.5 and in french system it is 2,5.

How can I localise the numbers?

Edit: I used the property NSLocale, but I am unable to format the resulted number into string.

Here is what I get after converting into string:

 NSString *localizedDecimalString = [NSString localizedStringWithFormat:@"%f",distance];

 result is 7 324,253011  //which is ok

and I want to append km at the end, so I tried to convert it back into double:

  double newlyChangedNumber = [localizedDecimalString doubleValue];

result is 7.0  //I should get 7324253011 here

How I can get something like 7 324,25 km?

Upvotes: 3

Views: 1258

Answers (2)

Daniel Klöck
Daniel Klöck

Reputation: 21137

You can "translate" numbers by using the locale.

For example to show a float you would do:

NSString *localizedString = [NSString localizedStringWithFormat:@"%3.2f", myNumber];

This method will use the system's locale(the result of [NSLocale currentLocale]). To use a custom locale either use initWithFormat:locale: or the initWithFormat:locale:arguments: method.

For more info read Formatting Data Using the Locale Settings.

UPDATE (adapted to the question's update)

to add km at the end, just edit the format string like this:

NSString *localizedDecimalString = [NSString localizedStringWithFormat:@"%f km",distance];

By the way, [localizedDecimalString doubleValue]; did not work because it expect a point (.) decimal separator and a coma thousands separator (,). Therefore, it just converted until it reached an unexpected character, in this case the space. So, from 7 324,253011 it only converted the 7. It would have worked with the english version (7,324.253011). To convert localized numbers' strings back to double/float, you would have to use a NSNumberFormatter.

Upvotes: 4

Aaron Brager
Aaron Brager

Reputation: 66242

NSNumberFormatter handles this. Just set the locale property appropriately.

See also the open-source FormatterKit, which can, for example, convert between "1st, 2nd, 3rd" and "1ère, 2ème, 3ème".

Upvotes: 1

Related Questions