views:

86

answers:

2

How do you print out leading zeros for a float using NSString type?

Input: 3.14 Desired Output: 03.1

Using Format: @"%02.1f" Output is 3.1

+2  A: 

You want @"04.1f". The 4 is the width.

Edited to add clarification regarding format strings.

As you can see from the documentation, the format strings conform to the IEEE printf specification.

The format string you've specified breaks down as follows: 0 -- Pad with zeros. 2 -- The entire resulting formatted value will have a minimum width of 2. .1 -- Precision of 1 digit following the decimal point.

imaginaryboy
Whoohoo!!! Thank you imaginaryboy! I misread the docs. %04.1f worked!
Dan
+1  A: 

For some reason you can't set the pre-decimal width on float numbers (maybe it's a bug you should report). This means you will have to split the number at the decimal format each the way you want and then merge them into one string (@"%i.%i", preDec, postDec).

It's not a bug. Whether it's what someone wants or not, it's how format strings are defined to work.
imaginaryboy
Still seems odd that it's not consistent between types. Perhaps a 'Feature Request' bug then...
It is consistent. For all types, the '2' he used specifies the minimum width of the resulting formatted value.
imaginaryboy