Correct use of the format specifier to display up to three decimal places, if necessary, otherwise decimal numbers?

I found% g to only show decimal numbers if necessary. If the number is an integer, then the final .000 is not added, so this is good. But in the case of, for example, 1.12345, I want it to shorten the answer to 1.123. And in the case of 1.000, I want to show only 1, as% g does.

I tried to specify% .3g in the string, but this does not work. If anyone has an answer, I would be grateful!

+5
source share
3 answers

I examined the capabilities of the "string format" using the IEEE Specification and, as I understand it, your desired behavior is not possible.

I recommend you use the NSNumberFormatter class. I wrote an example that matches your desired behavior. Hope this 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);
+11
source

What do you get for NSLog (@ "%. 3g", 1.12345)?

I did some tests, and as far as I understand, your question is 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".

+2
source

Jan 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)
0

All Articles