本文介绍了本地化一个浮点数,并在iOS中指定小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点数,我想显示一个小数位。例如。 104.8135674 ...以英语显示为104.8。通常我会使用:



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



但是,我想本地化该号码,所以我试过:



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



这样可以分配正确的十进制符号/ p>

英语:104.8



德语:104,8



但是,对于不使用(0123456789)的语言,使用正确的小数符号,但是例如



巴林 - 阿拉伯语:104,8(应使用不同的符号表示数字)



所以我试过:



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



但是我似乎不能指定小数位数。它给出例如。



英语:104.813

解决方案

NSNumberFormatter -setMaximumFractionDigits:用于这个目的,你可以重用相当不错的格式化程序:

  NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init]; 
[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:1];
[formatter setLocale:[NSLocale currentLocale]];
NSString * myString = [formatter stringFromNumber:[NSNumber numberWithFloat:123.456]];


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

解决方案

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]];

这篇关于本地化一个浮点数,并在iOS中指定小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 19:33