【问题标题】:Detect which side the current currency is on检测当前货币在哪一边
【发布时间】:2015-06-11 02:00:49
【问题描述】:

如何检查货币符号是否在哪一侧?例如,在美国,符号会是这样的:“$56.58”,但在法国会是这样的:“56.58€”。那么如何检测它是在右侧还是左侧呢?

NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setLocale:[NSLocale currentLocale]];

【问题讨论】:

  • 尝试找出价格字符串的第一个和最后一个字符的 ASCII 值。如果其中第一个的 ASCII 值不在 (48-57) 范围内,则货币符号位于左侧,否则位于右侧。
  • 你能给我看看样品吗?
  • 好奇 - 为什么你需要知道这个?
  • 我想要这个的原因是因为我有一个 UITextField 和一个 UILabel。标签将采用符号,而 textField 将是一笔钱。因此我需要知道标签应该在哪一边。您可能想知道为什么我只是跳过标签并格式化文本字段?答案是,因为这对我来说是不可能实现的。我试了几天没有成功。这就是为什么我要做这个“黑客”。
  • 不需要标签。只需将文本字段与货币格式化程序一起使用。如果您无法使其正常工作,请发布有关此问题的详细信息。

标签: ios objective-c nsnumberformatter


【解决方案1】:

如果您只想将数字格式化为货币,请将格式化程序的numberStyle 设置为NSNumberFormatterCurrencyStyle,然后使用其stringFromNumber: 方法。

如果出于某种原因,您确实想知道货币符号在格式化程序语言环境的格式中的位置,您可以向格式化程序询问其positiveFormat 并查找字符¤ (U+00A4货币符号)。

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterCurrencyStyle;

f.locale = [NSLocale localeWithLocaleIdentifier:@"en-US"];
NSLog(@"%@ format=[%@] ¤-index=%lu", f.locale.localeIdentifier, f.positiveFormat,
    (unsigned long)[f.positiveFormat rangeOfString:@"\u00a4"].location);

f.locale = [NSLocale localeWithLocaleIdentifier:@"fr-FR"];
NSLog(@"%@ format=[%@] ¤-index=%lu", f.locale.localeIdentifier, f.positiveFormat,
    (unsigned long)[f.positiveFormat rangeOfString:@"\u00a4"].location);

f.locale = [NSLocale localeWithLocaleIdentifier:@"fa-IR"];
NSLog(@"%@ format=[%@] ¤-index=%lu", f.locale.localeIdentifier, f.positiveFormat,
    (unsigned long)[f.positiveFormat rangeOfString:@"\u00a4"].location);

结果:

2015-06-10 21:27:09.807 commandline[88239:3716428] en-US format=[¤#,##0.00] ¤-index=0
2015-06-10 21:27:09.808 commandline[88239:3716428] fr-FR format=[#,##0.00 ¤] ¤-index=9
2015-06-10 21:27:09.808 commandline[88239:3716428] fa-IR format=[‎¤#,##0] ¤-index=1

请注意,在fa-IR 的情况下,符号不是格式字符串中的第一个或最后一个字符。第一个字符(索引为零处)是不可见的。这是 U+200E 从左到右的标记。

【讨论】:

  • 那么我可以做到以下几点:if ([f.positiveFormat rangeOfString:@"\u00a4"].location == 0)
  • 我想要这个的原因是因为我有一个 UITextField 和一个 UILabel。标签将采用符号,而 textField 将是一笔钱。因此我需要知道标签应该在哪一边。您可能想知道为什么我只是跳过标签并格式化文本字段?答案是,因为这对我来说是不可能实现的。我试了几天没有成功。这就是为什么我要做这个“黑客”。
  • 看看我的更新。我想你可以做类似if ([f.positiveFormat rangeOfString:@"\u00a4"].location < f.positiveFormat.length / 2) ....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多