I have read many question in stack overflow, what I want is remove 2 or more than two trailing zero behind the decimal. i.e:
12.00 ==> 12
12.30 ==> 12.30
12.35 ==> 12.35
12.345678 ==> 12.34
NSNumberFormatter *twoDecimalPlacesFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[twoDecimalPlacesFormatter setMaximumFractionDigits:2];
[twoDecimalPlacesFormatter setMinimumFractionDigits:0];
return [twoDecimalPlacesFormatter stringFromNumber:number];
I like @dorada's answer, here is a complete test:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
NSLog(@"12.00 ==> %@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.00]]);
NSLog(@"12.30 ==> %@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.30]]);
NSLog(@"12.35 ==> %@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.35]]);
NSLog(@"12.345678 ==> %@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345678]]);
NSLog output:
12.00 ==> 12
12.30 ==> 12.3
12.35 ==> 12.35
12.345678 ==> 12.35
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With