2011-12-13 11 views
6

मैं है निम्नलिखित कोड:उद्देश्य-सी stringvalue से डबल

double d1 = 12.123456789; 

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

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

मैं एक स्ट्रिंग मान है कि वास्तव में d1 रूप में ही है कैसे मिलता है?

उत्तर

6

के बारे में
NSString *test1 = [NSString stringWithFormat:@"%.15f", d1]; 

या बस डबल के रूप में

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

'% d' एक पूर्णांक – PengOne

+0

@PengOne मैंने तय किया है कि उसके लिए इसे '% lf', लंबे समय तक फ़्लोटिंग पॉइंट में परिवर्तित कर दिया गया है। –

+0

@ रिचर्ड जे। रौसीआईआई मेरी समझ यह है कि '% lf' केवल स्कैनिंग के दौरान आवश्यक है। – PengOne

11

यह एप्पल के String Format Specifiers के लिए गाइड पर एक नज़र लेने के लिए मदद मिल सकती है के लिए जाना कैसे।

%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 

इसके अलावा पाठ्यक्रम What Every Computer Scientist Should Know About Floating-Point Arithmetic की floating point (in)accuracy बारे में पढ़ें, और,।

यदि आप वास्तव में स्ट्रिंग को डबल से मिलान करना चाहते हैं, तो NSString का उपयोग एन्कोड करने के लिए करें और जब आप मान चाहते हैं तो doubleValue पर कॉल करें। NSNumberFormatter पर भी एक नज़र डालें।

संबंधित मुद्दे