繁体   English   中英

来自double的objective-c stringvalue

[英]objective-c stringvalue from double

我有以下代码:

double d1 = 12.123456789012345;

NSString *test1 = [NSString stringWithFormat:@"%f", d1]; // string is: 12.123457

NSString *test1 = [NSString stringWithFormat:@"%g", d1]; // string is: 12.1235

如何获得与d1完全相同的字符串值?

它可以帮助您查看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

还要了解浮点(in)精度 ,当然还有每个计算机科学家应该知道的关于浮点运算的内容

如果你真的希望字符串与double完全匹配,那么使用NSString对其进行编码,并在需要值时调用doubleValue 另请NSNumberFormatter

怎么样

NSString *test1 = [NSString stringWithFormat:@"%.15f", d1];

或者只是选择双倍

NSString *test1 = [NSString stringWithFormat:@"%lf", d1];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM