NSNumber 到 NSString(如果有小数则不带尾随零)
我正在努力解决这个问题,并且找不到任何资源: 我有一个 NSNumber
,我想在 UITextField
中显示它,以便用户可以编辑它。 所以我需要将此 NSNumber
转换为 NSString
,如下所示:
float value -> desired string value
1.0000000... -> 1
10.000000... -> 10
1.1230000... -> 1.123 or 1,123 depending on the locale
1000000.0... -> 1000000
我尝试使用 NSNumberFormatter
,但随后出现空格或逗号对于大数字:
1000000.0... -> 1,000,000 or 1 000 000 depending on the locale
我也尝试过
[NSString stringWithFormat:@"%g", val]
但是对于大数字我有一个科学的表达:
1000000.0 -> 1e+06
有人在这方面有成功的经验吗?
I'm struggling with this issue, and I couldn't find any resource for it :
I have an NSNumber
that I want to display in an UITextField
, so the user can edit it.
So I need to convert this NSNumber
to an NSString
, like this :
float value -> desired string value
1.0000000... -> 1
10.000000... -> 10
1.1230000... -> 1.123 or 1,123 depending on the locale
1000000.0... -> 1000000
I've tried to use NSNumberFormatter
, but then I get spaces or comas for big numbers :
1000000.0... -> 1,000,000 or 1 000 000 depending on the locale
I also tried
[NSString stringWithFormat:@"%g", val]
But then for big numbers I have a scientific expression :
1000000.0 -> 1e+06
Did somebody have a successful experience with this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSNumberFormatter
有这样的方法:我认为,您可以返回到您拥有的变体:
并使用该函数设置附加参数:
或者此外尝试此方法:
NSNumberFormatter
has such method as :I think, you can return to variant where you has:
and set additional parameter using that function:
Or moreover try this method:
NSNumberFormatter
是解决方案,您走在正确的道路上。但是:
NSLocale
信息还携带区域格式信息(使用美国区域设置或法国区域设置格式化数字会导致不同的格式和不同的表示形式)NSNumberFormatter
的选项来自定义格式,例如更改使用的分组分隔符、更改小数点分隔符等。这样您就可以真正自定义 NSNumberFormatter 将数值表示为字符串的方式。
NSNumberFormatter
is the solution, you were on the right path.But:
NSLocale
information also carries the Region Formatting info (formatting numbers using the US locale or the FR locale leads to different formats and different representations)NSNumberFormatter
, like changing the grouping separators used, changing the decimal separator, etc.This way you can really customize the way the
NSNumberFormatter
represents the numeric value into a string.尝试将 nsnumber 值转换为 NSInteger 或 CGFloat 并将其存储在新变量中。然后将转换后的变量设置为 uitextfield。
我认为它应该适合你..!!
try converting nsnumber value to NSInteger or CGFloat and store it in the new variables. Then set the converted variables to uitextfield.
I think it should work for you..!!