舍入用于NSString中的双精度数

时间:2011-12-03 21:44:18

标签: objective-c nsstring double rounding

我的情况是,我有很多不同的double值,例如1.00, 0.25 and 2.50。我想围绕这些doubles,以便它们成为1, 0.25 and 2.5;换句话说,我想删除任何尾随的0。有没有办法做到这一点?

目前我一直在使用%.2f,我想知道我是否可以利用这个但是以某种方式对其进行调整。请有人帮帮我吗?

4 个答案:

答案 0 :(得分:12)

只要您只谈论显示,这很容易。您想要的format specifier%g

  

对于f转换,double参数应以样式eF(或样式EG转换说明符),精度指定有效位数[...] 尾随零应从结果的小数部分删除 [...]

double twopointfive = 2.500;
double onepointzero = 1.0;
double pointtwofive = .25000000000;
NSLog(@"%g %f", twopointfive, twopointfive);
NSLog(@"%g %f", onepointzero, onepointzero);
NSLog(@"%g %f", pointtwofive, pointtwofive);
  

2011-12-06 21:27:59.180 TrailingZeroes [39506:903] 2.5 2.500000
  2011-12-06 21:27:59.184 TrailingZeroes [39506:903] 1 1.000000
  2011-12-06 21:27:59.185 TrailingZeroes [39506:903] 0.25 0.250000

相同的格式说明符可以与NSNumberFormatter一起使用,这也可以控制有效数字。

当然,无法从数字存储在内存中的方式中删除尾随零。

答案 1 :(得分:2)

我相信您希望%g格式说明符可以编辑尾随零。

答案 2 :(得分:1)

不是真的四舍五入,但是你只试过%f它应该只显示所需的位数而不是填充数字。

我上面的回答是错误的,%g正如其他人所说的那样是正确的方法。

字符串格式化程序的文档也应该有所帮助。 http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265

答案 3 :(得分:1)

以下是您可以使用的所有格式说明符的列表...

%@     Object
%d, %i signed int
%u     unsigned int
%f     float/double

%x, %X hexadecimal int
%o     octal int
%zu    size_t
%p     pointer
%e     float/double (in scientific notation)
%g     float/double (as %f or %e, depending on value)
%s     C string (bytes)
%S     C string (unichar)
%.*s   Pascal string (requires two arguments, pass pstr[0] as the first, pstr+1 as the second)
%c     character
%C     unichar

%lld   long long
%llu   unsigned long long
%Lf    long double