bladnman
bladnman

Reputation: 2651

Objective-C float string formatting: Formatting the whole numbers

There are some great answers here about how to format the decimal places of a float for a string:

float myFloatA = 2.123456f;
NSLog(@"myFloatA: [%.2f]", myFloatA;
// returns:
// myFloatA: [2.12]

But what I'm looking for is how to format the whole numbers of the same float. This can be done with the same sort of trick on an integer:

int myInt = 2;
NSLog(@"myInt: [%5d]", myInt;
// returns:
// myInt: [    2]

So I was hoping something like a %5.2f would be the answer to formatting both before and after the decimal. But it doesn't:

float myFloatA = 2.123456f;
NSLog(@"myFloatA: [%5.2f]", myFloatA;
// returns:
// myFloatA: [2.12]

Any thoughts on this one?

Upvotes: 1

Views: 726

Answers (2)

AndrewPK
AndrewPK

Reputation: 6150

Also confirmed that this works. If you're worried you're not getting 5 character width, try forcing zero padding with:

NSLog(@"myFloatA: [%05.2f]", myFloatA);

Upvotes: 0

Abizern
Abizern

Reputation: 150615

Using the print specifiers is all very well for NSLogs, but think about this another way.

Usually, you want a string representation of a number when you are displaying it in something like a text field. In which case, you might as well use an NSNumberFormatter which does most of the heavy lifting for you.

Upvotes: 1

Related Questions