Question

I am trying to get number in 2 decimal places with trailing zeros.

e.g

 11.633-> 11.63
 11.630-> 11.63
 11.60-> 11.6
 11-> 11
 12928.98-> 12928.98

for this I written below line

 #define kFloatFormat2(x) [NSString stringWithFormat:@"%g", [[NSString stringWithFormat:@"%.2f", x] floatValue]]

    NSNumber *number1 = [NSNumber numberWithDouble:12928.98];
    NSLog(@"number1:%@", number1);
    NSString *string1 = kFloatFormat2([number1 floatValue]);
    NSLog(@"string1:%@", string1);

the output of above prints

number1:12928.98

string1:12929

Why it prints 12929 value for string1 I want it as 12928.98.

Was it helpful?

Solution

Have you tried using a number formatter?

NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesGroupingSeparator:NO];
[formatter setMaximumFractionDigits:fractionDigits];
[formatter setMinimumFractionDigits:fractionDigits];

Now do something like

NSNumber *x = @23423;
NSString *value = [formatter stringFromNumber:x];
NSLog(@"number = %@, value);

OTHER TIPS

You macro makes no sense. Just make it:

#define kFloatFormat2(x) [NSString stringWithFormat:@"%.2f", [x floatValue]]

where x is an NSNumber. And then you would call it like this:

NSString *string1 = kFloatFormat2(number1);

Or just do this:

double x = 12928.98;
NSLog(@"number = %.2f", x);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top