views:

816

answers:

3

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?

+1  A: 

Look up NSNumberFormatter.

NSResponder
+2  A: 

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

Mark Bessey
I actually thought I had tried %g. I just tried it like this: [answer setStringValue:[NSString stringWithFormat:@"%2.02g", answerFloat]];and it worked like a charm. thanks!
Adam Tootle
+2  A: 

For the greatest flexibility, you could consider implementing a custom subclass of NSFormatter. There might be other salient tips in the Data Formatting Programming Guide for Cocoa.

mrkj