Lenny Magico
Lenny Magico

Reputation: 1203

Xcode decimal places

I would like to display the a number value to the max number of decimal places. If you don't format the float to:

@"%.1f"

then it will display the number as e.g. 1.000000. What I would like is that the number would have the max number of decimal places it needs e.g.

1 would not need any

1.5 would need 1 decimal place

1.24 would need 2 decimal places

Is there some sort of code that formats the number to the max number of decimal places?

Upvotes: 2

Views: 2781

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

Replace "f" with "g".

From 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.

Upvotes: 4

Related Questions