如何在目标C中的每3位数字前添加逗号? [英] How to add commas to number every 3 digits in Objective C?

查看:86
本文介绍了如何在目标C中的每3位数字前添加逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个数字int aNum = 2000000,如何格式化该数字,以便可以将其显示为2,000,000 NSString?

解决方案

请勿自行设置数字格式.几乎可以肯定,您将无法正确处理所有边缘情况或正确处理所有可能的语言环境.使用 NSNumberFormatter 用于将数字数据格式化为本地化的字符串表示形式.

您将使用NSNumberFormatter实例方法-setGroupingSeparator:将分组分隔符设置为@","(或者更好的是[[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];感谢@ntesler),并使用-setGroupingSize:每三位数放置一个分组分隔符. /p>

If I have a number int aNum = 2000000 how do I format this so that I can display it as the NSString 2,000,000?

解决方案

Don't do your own number formatting. You will almost certainly not get all the edge cases right or correctly handle all possible locales. Use the NSNumberFormatter for formatting numeric data to a localized string representation.

You would use the NSNumberFormatter instance method -setGroupingSeparator: to set the grouping separator to @"," (or better yet [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator]; thanks @ntesler) and -setGroupingSize: to put a grouping separator every 3 digits.

这篇关于如何在目标C中的每3位数字前添加逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆