0
votes

So I've coded a calculator in objective C and I've formatted the display in .4g as I wanted only significant digits and 4 decimal places. This works fine :) What I would like it to do is not display 2.34E+05 etc when it displays a longer number like 234,000. I've allowed it to autosize the text in the label so I know it isn't just that the label is too small. Is there a piece of code that will make it display the actual number instead of the scientific notation?

1

1 Answers

1
votes

Formatting with %f instead of %g won't use standard form.

Have a look at this specification.


Edit 1:

I found this answer to help with the rounding.

-(float) round:(float)num toSignificantFigures:(int)n {
    if(num == 0) {
        return 0;
    }

    double d = ceil(log10(num < 0 ? -num: num));
    int power = n - (int) d;

    double magnitude = pow(10, power);
    long shifted = round(num*magnitude);
    return shifted/magnitude;
}

I then combined these two options to get:

NSLog(@"%.0f", [self round:number toSignificantFigures:4]); 

Edit 2:

What about this:

- (NSString *) floatToString:(float) val {
    NSString *ret = [NSString stringWithFormat:@"%.5f", val];
    unichar c = [ret characterAtIndex:[ret length] - 1];
    while (c == 48 || c == 46) { // 0 or .
        ret = [ret substringToIndex:[ret length] - 1];
        c = [ret characterAtIndex:[ret length] - 1];
    }
    return ret;
}

I haven't tested this, but it looks as if it limits decimals to 5, then removes any trailing zeros or decimal points.

[Source]