[英]objective-c stringvalue from double
I have the following code: 我有以下代码:
double d1 = 12.123456789012345;
NSString *test1 = [NSString stringWithFormat:@"%f", d1]; // string is: 12.123457
NSString *test1 = [NSString stringWithFormat:@"%g", d1]; // string is: 12.1235
How do I get a string value that is exactly the same as d1? 如何获得与d1完全相同的字符串值?
It may help you to take a look at Apple's guide to String Format Specifiers . 它可以帮助您查看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
Also read up on floating point (in)accuracy , and, of course What Every Computer Scientist Should Know About Floating-Point Arithmetic . 还要了解浮点(in)精度 ,当然还有每个计算机科学家应该知道的关于浮点运算的内容 。
If you really want the string to match the double exactly, then use NSString
to encode it and call doubleValue
when you want the value. 如果你真的希望字符串与double完全匹配,那么使用NSString
对其进行编码,并在需要值时调用doubleValue
。 Also take a look at NSNumberFormatter
. 另请NSNumberFormatter
。
How about 怎么样
NSString *test1 = [NSString stringWithFormat:@"%.15f", d1];
Or simply go for the double as 或者只是选择双倍
NSString *test1 = [NSString stringWithFormat:@"%lf", d1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.