ios - iPhone : How to get number from string with

我正在尝试从带有货币符号的字符串中获取数字(浮点值)。

例如。 从“¥1,234”到1234 从“3,456 澳元”到 3456 从“56.78€”到 56.78

我尝试了以下代码,但结果为 0。

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setLenient:YES];
NSNumber *number = [formatter numberFromString:text];
NSDecimalNumber *money = [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]];
float fval = [money floatValue];

提前致谢!

最佳答案


这里的困难在于不同国家的货币小数分隔符不同。更糟糕的是,某些地区使用的数字分组符号在其他地区用作小数分隔符。见:

http://en.wikipedia.org/wiki/Decimal_mark#Hindu.E2.80.93Arabic_numeral_system

http://en.wikipedia.org/wiki/Decimalisation#Decimal_currency

因此,依赖小数分隔符的符号或使用可疑小数标记后的小数位数的幼稚方法可能不是 100% 准确的。如果您要处理特定的子集,请务必使用某种启发式方法。

但是,考虑到全局问题空间,我认为最好的办法是使用区域设置(如果有的话):

NSString* text =  @"$3,456.78 USD";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
text = [text stringByReplacingOccurrencesOfString:formatter.internationalCurrencySymbol withString:@""];
float fval = [formatter numberFromString:text].floatValue;

关于ios - iPhone : How to get number from string with currency symbol in Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999715/

相关文章:

xml - 如何使用 gVim 格式化未格式化的 XML 文档?

Python 浮点格式 - 类似于 "g",但数字更多

html - 用于 HTML 和 CSS 中的双面打印的甚至分页符

formatting - 从 Mathematica 导出自定义格式的表达式

c# - DataGridViewCheckBoxColumn : FormatException

formatting - 如何在我的博客文章中使用 stackoverflow 样式标记?

c# - 使用 String.Format 时,如果字符串值不为 null 或为空,是否有一种简单的

python - 在 Python 中口头格式化数字

string - 什么函数用于格式化/替换 Grails/Groovy 中字符串中的 {0} {1}

vim - 使用 Vim,是否有更有效的方法来根据这个最佳实践来格式化 LaTeX 段落?