Formatting floats in Objective C

Viewed 43598

I need to format a float (catchy title, he?) to 2 decimal places, but only if those decimal places have values that aren't zero. Example:

I have a NSTextField named 'answer', after I do some math with a couple of floats, I want to assign my 'answerFloat' variable to the 'answer' NSTextField. So far I've got:

[answer setStringValue:[NSString stringWithFormat:@"%.2f", answerFloat]];

But that sets something like 45 to 45.00. I want whole numbers to be displayed without the zeroes, and any decimal numbers to be displayed with their respective decimal values.

Do I need to run some kind of check before giving it to stringWithFormat? Or does NSString offer a way to handle this?

4 Answers

Have you tried the %g format specifier?

NSLog([NSString stringWithFormat:@"%g, %g", 45.0, 45.5]);

2010-01-12 19:54:38.651 foo[89884:10b] 45, 45.5

Related