Pergunta

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:

  • I need the double to have 6 digits of decimal precison.
  • If the double exceeds 15 digits including decimals, it should turn over to scientific notation with 6 digits of precision. e.g. 1.234567E10.
  • There should be commas for numbers less than 15 digits.

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

Foi útil?

Solução

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];
}

Outras dicas

I am not sure if this is the best way to do this but it does work:

    if ([[num stringValue] rangeOfString:@"e"].location == NSNotFound) {
        formatter.numberStyle = NSNumberFormatterDecimalStyle;
        NSLog(@"%@", [formatter stringFromNumber:num]);
    } else {
        formatter.positiveFormat = @"0.000000E0";
        formatter.roundingMode = NSNumberFormatterRoundDown;
        NSLog(@"%@", [formatter stringFromNumber:num]);
    }

If num = NSNumber *num = [NSNumber numberWithDouble:12345678901234567];

Would return: 1.234567E16

if num = NSNumber *num = [NSNumber numberWithDouble:123456.382];

Would return: 123,456.382

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top