开发者

NumberFormatter - ObjectiveC

开发者 https://www.devze.com 2023-02-06 06:40 出处:网络
How do I create a number formatter for formatting large numbers with comma开发者_开发知识库s?

How do I create a number formatter for formatting large numbers with comma开发者_开发知识库s?

For example, 2389378.289 should become 2,389,378.289

Note that there is not always three decimal places, nor is there always a decimal at all. Please use NSNumberFormatter.

Thanks!


NSNumberFormatter *fmt = [[[NSNumberFormatter alloc] init] autorelease];
[fmt setAlwaysShowsDecimalSeparator:NO];
[fmt setFormat:@"#,##0.###"];
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:35.424252]]);
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:21.3]]);
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:10392425]]);

The format Chuck gave you supports up to 3 decimal places. If you have a number with less than 3 they just don't show up. Chuck is also correct that you want to take a look at the Unicode number format guide, it is invaluable for number formatting issues.


The format for that would be @"#,##0.###". Take a look at the Unicode number format guide for a full explanation of how to construct format strings.

(Also note that this works correctly in locales where commas and dots are reversed, or where other characters are used.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号