I've found %g to show only decimals if needed. If the number is whole, no trailing .000 is added, so thats good. But in the case of for example 1.12345 I want it to short the answer to 1.123. And in the case of 1.000 I want to only show 1, as %g already does.
I've tried to specify %.3g in the string, but that doesn't work. If anyone has the answer, I'd be grateful!
I reviewed the abilities of a "format string" via the IEEE Specification and as I understand it your wished behavior is not possible.
I recommend to you, to use the NSNumberFormatter class. I wrote an example that matches your wished behavior. I hope that helps:
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setDecimalSeparator:@"."];
[numberFormatter setGroupingSeparator:@""];
NSString *example1 = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:123456.1234]];
NSLog(@"%@", example1);
NSString *example2 = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:123456.00]];
NSLog(@"%@", example2);
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