Question

Is there a way to use scientific notation in objective c and have it display three significant digits only? What I am current using is:

string = [NSString stringWithFormat:@"%e", floatNumber];
// floatNumber = 100000; string = 1.000000e+06

I just want string = 1.00e+06

Was it helpful?

Solution

Use the format specifier ".2" as follows:

    string = [NSString stringWithFormat:@"%.2e", floatNumber];

From apple's documentation:

The format specifiers supported by the NSString formatting methods and CFString formatting functions follow the IEEE printf specification...

And from the IEEE printf specification, if you read under the Description section, you will find:

e, E

The double argument shall be converted in the style "[-]d.ddde±dd", where there is one digit before the radix character (which is non-zero if the argument is non-zero) and the number of digits after it is equal to the precision; if the precision is missing, it shall be taken as 6; if the precision is zero and no '#' flag is present, no radix character shall appear. The low-order digit shall be rounded in an implementation-defined manner. The E conversion specifier shall produce a number with 'E' instead of 'e' introducing the exponent. The exponent shall always contain at least two digits. If the value is zero, the exponent shall be zero.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top