问题
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!
回答1:
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);
回答2:
What do you get for NSLog(@"%.3g", 1.12345)?
I did some tests and as I understand your question you're on the right track. These are my results:
NSLog(@"%g", 1.000000); => 1
NSLog(@"%g", 1.123456789); => 1.12346
NSLog(@"%.1g", 1.123456789); => 1
NSLog(@"%.2g", 1.123456789); => 1.1
NSLog(@"%.3g", 1.123456789); => 1.12
NSLog(@"%.4g", 1.123456789); => 1.123
To get what you want use @"%.4g".
回答3:
Here is Jan's solution for Swift 4:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 2
numberFormatter.decimalSeparator = "."
numberFormatter.groupingSeparator = ""
let example1 = numberFormatter.string(from: 123456.1234)!
print(example1)
let example2 = numberFormatter.string(from: 123456.00)!
print(example2)
来源:https://stackoverflow.com/questions/7271560/correct-use-of-format-specifier-to-show-up-to-three-decimals-if-needed-otherwis