Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove More Than 2 Trailing zero

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
like image 485
Lunayo Avatar asked Apr 26 '26 10:04

Lunayo


2 Answers

NSNumberFormatter *twoDecimalPlacesFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[twoDecimalPlacesFormatter setMaximumFractionDigits:2];
[twoDecimalPlacesFormatter setMinimumFractionDigits:0];

return [twoDecimalPlacesFormatter stringFromNumber:number];
like image 165
Daniel Broad Avatar answered Apr 29 '26 03:04

Daniel Broad


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
like image 33
zaph Avatar answered Apr 29 '26 03:04

zaph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!