Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localize a float and specify number of decimal places in iOS

I have a float that I'd like to display to one decimal place. E.g. 104.8135674... to be displayed as 104.8 in English. Usually I'd use:

myString = [NSString stringWithFormat:@"%.1f",myFloat];

However, I'd like to localize the number, so I tried:

myString = [NSString localizedStringWithFormat:@"%.1f",myFloat];

This works to assign the correct decimal symbol (e.g.

English: 104.8

German: 104,8

However, for languages that use don't use arabic numerals (0123456789), the correct decimal symbol is used, but the numbers are still in arabic numerals. e.g.

Bahrain-Arabic: 104,8 (it should use different symbols for the numbers)

So I tried:

myString = [NSNumberFormatter localizedStringFromNumber:[NSNumber numberWithFloat:myFloat] numberStyle:kCFNumberFormatterDecimalStyle];

But with that I can't seem to specify the number of decimal places. It gives e.g.

English: 104.813

like image 212
MattyG Avatar asked Jul 16 '12 11:07

MattyG


People also ask

How do you round a float to 2 decimal places in Swift?

By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

How do you truncate decimals in Swift?

Just floor (round down) the number, with some fancy tricks. So, multiply by 1 and the number of 0s being the decimal places you want, floor that, and divide it by what you multiplied it by. And voila.


1 Answers

NSNumberFormatter -setMaximumFractionDigits: is used for that purpose and you can reuse the formatter which is quite good:

NSNumberFormatter * formatter =  [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:1];
[formatter setLocale:[NSLocale currentLocale]];
NSString * myString = [formatter stringFromNumber:[NSNumber numberWithFloat:123.456]];
like image 57
A-Live Avatar answered Oct 12 '22 22:10

A-Live