Reputation: 340
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.
Upvotes: 1
Views: 2276
Reputation: 2052
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);
Upvotes: 3
Reputation: 318794
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);
Upvotes: 3