Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of format specifier to show up to three decimals if needed, otherwise zero decimals?

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!

like image 691
Anders Lindsetmo Avatar asked Sep 01 '11 14:09

Anders Lindsetmo


1 Answers

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);
like image 74
Jan Weinkauff Avatar answered Oct 12 '22 23:10

Jan Weinkauff