0

For the code below:

double j1;

j1=7000000    //example
ItemE[5]=[NSString stringWithFormat:@"@1. total inc = %g", j1];

ItemE[5] is returned as "1.total inc = 7e +06"

How do I prevent the scientific notation and have "1.total inc = 7000000" instead?

2 Answers 2

4

Use %f:

ItemE[5]=[NSString stringWithFormat:@"@1. total inc = %f", j1];

Edit:

If you don't want decimal places you should use:

ItemE[5]=[NSString stringWithFormat:@"@1. total inc = %.f", j1];

To elaborate, you were using wrong specifier in format string.%g instructs to create string representation of floating-point variable in scientific notation. Normally you should use %f to represent double and float variable. By default, this specifier will result in number with 6 decimal places. In order to change that you can modify that specifier, for example:

%5.3f means that string should have 3 decimal places and should be 5 characters long. That means that if representation would be shorter than 5 chars, string will have additional spaces in front of number to give 5 chars total. Note that if you will have large number, it'll not be truncated. Consider code:

double pi = 3.14159265358979323846264338327950288;
NSLog(@"%f", pi);
NSLog(@"%.3f", pi);
NSLog(@"%8.3f", pi);
NSLog(@"%8f", pi);
NSLog(@"%.f", pi);

will give result:

3.141593
3.142
   3.142
3.141593
3
Sign up to request clarification or add additional context in comments.

5 Comments

And, for reference, the docs for stringWithFormat: have a link to a “String Format Specifiers” page.
@Phillip Mils well, then i get 7000000.000000 I don't need the after the decimal point digits. do i need to convert to to integer or is there a format way here ?
Got to the link that @Vervious gave you and then click on where it says, "For more details, see the IEEE printf specification."
@Johnnywho, yes, i just got the same after digging some more :). ty.
2

please, try to use this one:

double j1 = 7000000.f;
NSLog(@"1. total inc = %.f", j1);

the result will be:

1. total inc = 7000000

I hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.