2011-09-26 109 views
3

我希望你能幫助我解決這個「小問題」。我想將一個字符串轉換爲double/float。要加倍的字符串

NSString *stringValue = @"1235"; 
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/(double)100.00]; 

我希望這對priceLabel設置爲12,35,但我得到一些奇怪的長字符串的意思與我無關。

我曾嘗試:

priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue intValue]/(double)100.00]; 

priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/100]; 

但都沒有成功。

+0

結帳這個問題:http://stackoverflow.com/questions/169925/how-to-do-string-conversions-in-objective- c ...您需要爲用戶在其設置中設置的語言環境設置一個「NSNumberFormatter」,並使用它來獲取字符串中的信息。 – klaustopher

回答

13

您必須使用%f來顯示float/double值。

然後%.2f點後意味着2digits

NSString *stringValue = @"1235"; 

NSString *str = [NSString stringWithFormat:@"%.2f",[stringValue doubleValue]/(double)100.00]; 

NSLog(@"str : %@ \n\n",s); 

priceLabel.text = str; 

OUTPUT:

STR:12.35

+0

謝謝分配!這對我有效! –

+0

然後你可以通過勾選mark.thanks來標記這個答案。 –

+0

即時幫助http://chat.stackoverflow.com/rooms/682/conversation/do-u-want-instant-help-for-ur-question-or-ru-new-bee-to-iphone-ipad-開發 –

1

我想你錯了格式字符串。當您有:

[NSString stringWithFormat:@"%d", ...]; 

你要真有:

[NSString stringWithFormat:@"%f", ...]; 

%d用於整數值。但是你試圖顯示一個浮點數(%f)。

14

這是如何轉換NSStringdouble

double myDouble = [myString doubleValue]; 
+2

奇怪的問題是字符串翻倍。接受的答案甚至沒有解決這個問題。但是這裏有一個。 :) 謝謝 – Houman