Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

ios - NSNumberFormatter with comma decimal separator

I tried to convert an NSString like "12000.54" into "12.000,54". I wrote an NSNumberFormatter instance.

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSeparator:@"."];
[formatter setDecimalSeparator:@","];

But when I NSLog this :

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

It prints null value. If I change my comma with a point it's working correctly. I just would like to be able to put what I want for my separators field (comma, point, slash, etc ...) and I have different outputs : 12/000,54 12.000.54 12,000,54 for example.

Do you know how I can handle this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would recommend not hardcoding the separator to ensure the right separator behavior based on the iPhone locale setting. The easiest way to to this is:

using objective-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

using 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

and I would not use the var-name "numberFromString" because it is an NSNumberFormatter method. Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...