Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting floats in Objective C

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?

like image 383
Adam Tootle Avatar asked Jan 13 '10 03:01

Adam Tootle


2 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

like image 58
Mark Bessey Avatar answered Oct 14 '22 05:10

Mark Bessey


The problem with %g is that it doesn't have a way to specify the rounding increment (at least, not that I can find).

You can use NSNumberFormatter like this to achieve your result with a number that has an undefined number of decimal places.

double none = 5;
double one = 5.1;
double two = 5.01;
double lots = 5.918286558251858392107584219;

NSNumber *numberNone = [NSNumber numberWithDouble:none];
NSNumber *numberOne = [NSNumber numberWithDouble:one];
NSNumber *numberTwo = [NSNumber numberWithDouble:two];
NSNumber *numberLots = [NSNumber numberWithDouble:lots];

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.roundingIncrement = [NSNumber numberWithDouble:0.01];
formatter.numberStyle = NSNumberFormatterDecimalStyle;

NSLog(@"%@",[formatter stringFromNumber:numberNone]);
NSLog(@"%@",[formatter stringFromNumber:numberOne]);
NSLog(@"%@",[formatter stringFromNumber:numberTwo]);
NSLog(@"%@",[formatter stringFromNumber:numberLots]);

Output:

2012-02-15 16:21:17.469 AwakeFromNib[53043:f803] 5
2012-02-15 16:21:17.470 AwakeFromNib[53043:f803] 5.1
2012-02-15 16:21:17.470 AwakeFromNib[53043:f803] 5.01
2012-02-15 16:21:17.471 AwakeFromNib[53043:f803] 5.92
like image 23
Mark Suman Avatar answered Oct 14 '22 05:10

Mark Suman