ios – NSNumberFormatter用逗号小数点分隔符

前端之家收集整理的这篇文章主要介绍了ios – NSNumberFormatter用逗号小数点分隔符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将NSString像“12000.54”转换成“12.000,54”.我写了一个NSNumberFormatter实例.
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSeparator:@"."];
[formatter setDecimalSeparator:@","];

但是当我NSLog这个:

NSLog(@"%@",[formatter stringFromNumber:[formatter numberFromString:value]]);

它打印空值.如果我改变一个逗号,它的工作正常.我只想把我想要的分隔符字段(逗号,点,斜杠等)放在我身上,我有不同的输出:例如12 / 000,54 12.000.54 12,000,54.

你知道我能如何处理这个问题吗?

解决方法

我建议不要对分隔符进行硬编码,以确保基于iPhone区域设置的正确的分隔符行为.最简单的方法是:

使用目标c

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
numberFormatter.locale = [NSLocale currentLocale];// this ensures the right separator behavior
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
numberFormatter.usesGroupingSeparator = YES;

// example for writing the number object into a label
cell.finalValueLabel.text = [NSString StringWithFormat:@"%@",[numberFormatter stringForObjectValue:numberFromString]]; // your var name is not well chosen

使用SWIFT 3

let formatter = NumberFormatter()
 formatter.locale = NSLocale.current // this ensures the right separator behavior
 formatter.numberStyle = NumberFormatter.Style.decimal
 formatter.usesGroupingSeparator = true

 // example for writing the number object into a label
 // your variable "numberFromString" needs to be a NSNumber object
 finalValueLabel.text = formatter.string(from: numberFromString)! // your var name is not well chosen

并且我不会使用var-name“numberFromString”,因为它是一个NSNumberFormatter方法.祝你好运!

猜你在找的iOS相关文章