Shi*_*eld 7 iphone double objective-c stringwithformat ios
我有以下代码:
double d1 = 12.123456789012345;
NSString *test1 = [NSString stringWithFormat:@"%f", d1]; // string is: 12.123457
NSString *test1 = [NSString stringWithFormat:@"%g", d1]; // string is: 12.1235
Run Code Online (Sandbox Code Playgroud)
如何获得与d1完全相同的字符串值?
Pen*_*One 12
它可以帮助您查看Apple的字符串格式说明符指南.
%f 64-bit floating-point number
%g 64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise
Run Code Online (Sandbox Code Playgroud)
还要了解浮点(in)精度,当然还有每个计算机科学家应该知道的关于浮点运算的内容.
如果你真的希望字符串与double完全匹配,那么使用NSString它来编码并doubleValue在你想要值时调用.另外看一看NSNumberFormatter.
怎么样
NSString *test1 = [NSString stringWithFormat:@"%.15f", d1];
Run Code Online (Sandbox Code Playgroud)
或者只是选择双倍
NSString *test1 = [NSString stringWithFormat:@"%lf", d1];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18236 次 |
| 最近记录: |