0

I'm trying to display very small double value on a TextField. For example, doCalculationForEqualPressed function returns 0.00008, but when I display it on a text field it shows a exponential record (8e-05). I don't need the number to be shown in exponential view. How to set the precision when to use exponential record ???

Using specifier %.9g - doesn't help.

double result;
result = [self.brain doCalculationForEqualPressed:[self.brain operationArray]];

if (result == INFINITY || result == -INFINITY || isnan(result)){
    NSString *infinity = @"\u221E";
    self.displayField.text = [NSString stringWithFormat:@"%@", infinity];
}
else
    self.displayField.text = [NSString stringWithFormat:@"%.9g", result];
Rashad
  • 11,057
  • 4
  • 45
  • 73
eglerion
  • 1
  • 1

1 Answers1

0

It can't be done with a format specifier by default.

You need to use sprintf and then remove the trailing zeros yourself.

char str[50];
sprintf (str,"%.20g",num);  // Make the number.
morphNumericString (str, 3);

void morphNumericString (char *s, int n) {
    char *p;
    int count;

    p = strchr (s,'.');         // Find decimal point, if any.
    if (p != NULL) {
        count = n;              // Adjust for more or less decimals.
        while (count >= 0) {    // Maximum decimals allowed.
             count--;
             if (*p != '\0')    // If there's less than desired.
                 break;
             p++;               // Next character.
        }

        *p-- = '\0';            // Truncate string.
        while (*p == '0')       // Remove trailing zeros.
            *p-- = '\0';

        if (*p == '.') {        // If all decimals were zeros, remove ".".
            *p = '\0';
        }
    }
}

See this answer

https://stackoverflow.com/a/277810/569497

Community
  • 1
  • 1
Selvin
  • 12,333
  • 17
  • 59
  • 80