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?

4

2 に答える 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
于 2012-08-11T16:08:52.673 に答える
2

これを使ってみてください:

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

結果は次のようになります。

1. total inc = 7000000

お役に立てば幸いです。

于 2012-08-11T19:05:52.967 に答える