Xcode小数位

时间:2011-03-14 16:54:27

标签: objective-c xcode decimal max

我想将数字值显示为最大小数位数。如果不将浮动格式化为:

@"%.1f"
然后它会将数字显示为例如1.000000。我想要的是该数字将具有所需的最大小数位数,例如。

1不需要任何

1.5需要1位小数

1.24需要2位小数

是否有某种代码将数字格式化为最大小数位数?

1 个答案:

答案 0 :(得分:4)

将“f”替换为“g”。

来自printf(3)

 gG      The double argument is converted in style f or e (or F or E for G conver-
         sions).  The precision specifies the number of significant digits.  If the
         precision is missing, 6 digits are given; if the precision is zero, it is
         treated as 1.  Style e is used if the exponent from its conversion is less
         than -4 or greater than or equal to the precision.  Trailing zeros are removed
         from the fractional part of the result; a decimal point appears only if it is
         followed by at least one digit.