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?
Asked
Active
Viewed 821 times
1 Answers
1
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.

Community
- 1
- 1

James Webster
- 31,873
- 11
- 70
- 114
-
but then %f displays number like 234.00000 and i don't want the non significant digits? – Craig Aug 13 '12 at 08:49
-
You can still use the `%.4f` to limit decimals. – James Webster Aug 13 '12 at 08:52
-
I would try just changing that `g` to an `f` – James Webster Aug 13 '12 at 09:03
-
That limits decimals but still displays insignificant 0 after the decimal place.... – Craig Aug 13 '12 at 09:05
-
Yeah, noticed that was stupid of me to ask i thought you could use 2 parameters, but those 2 wouldnt work in conjunction anyway. >.< but yeah f doesn't remove insignificant digits so i get 234.00000. Limiting decimals isnt the issue it's removing non significant digits – Craig Aug 13 '12 at 09:11
-
Sort of, but i don't want to limit the amount of sig figs, i want to limit the amount of non sig figs to 0 lol. I could just leave it using the e+05 thing as it seems to be such a pain but it just doesn't look right to me >. – Craig Aug 13 '12 at 09:42
-
I'm sure that'd do it if it does what you say it does, i have no idea how to put that into my program atm though, only been learning for a week >. – Craig Aug 13 '12 at 10:55