I have the following situation I need help solving. I have a double that can exceed 15 digits with no decimals or can have decimals but doesn't exceed 15 digits. Here are the conditions I need met:
1.234567E10
.e.g. if the number was 123456.382
it should be formatted as 123,456.882
.
If the number was 12345678901234567
it should be formatted as 1.234567E16
. Also if it had decimals, they should be ignored.
It tried creating a string from the double with the format specifier %1.6g
. This works for the decimal numbers, but once the number exceeds 6 digits e.g. 100,000
, it turns into scientific notation. How can I achieve my desired results?
Edit: the type of scientific notation doesn't matter. i.e. I don't care whether it's ...E10
or ...e+10
If the double exceeds 15 digits including decimals, it should turn over to scientific notation with 6 digits of precision.
Do you mean always 6 fractional digits but if the integer part exceeds 9 digits, then go to scientific notation? If so, then here's my solution.
NSString *numberToString(NSNumber *number) {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
// If number has (15 - 6) or less integer digits
if ([number integerValue] < 1E9) {
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesGroupingSeparator:YES];
} else {
[formatter setNumberStyle:NSNumberFormatterScientificStyle];
}
[formatter setMinimumFractionDigits:6];
[formatter setMaximumFractionDigits:6];
return [formatter stringFromNumber:number];
}