2010-10-26 12 views
3

我按下一個號碼時執行的代碼塊:此字符串格式有什麼問題(模擬器和設備上的不同行爲)?

NSString *currentValue = [@"" stringByAppendingFormat:@"%.02f", [[[[[textField text] stringByReplacingOccurrencesOfString:@"." withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] doubleValue]/100.0f]; 
      //I am using this to obtain always a number with 2 decimals. 

    NSNumberFormatter *f = [[NSNumberFormatter alloc] init]; 
    [f setNumberStyle:NSNumberFormatterDecimalStyle]; 
    [f setMinimumFractionDigits:2]; 
    [f setMaximumFractionDigits:2]; 
    [f setGroupingSeparator:@" "]; 

    NSNumber *currentNumberValue = [f numberFromString:currentValue]; 
    NSLog(@"1: %@", currentValue); 
    NSLog(@"2: %@", [currentNumberValue stringValue]); 

現在,如果我在模擬器中運行這個並按3我得到如下結果:

1: 0.03 
2: 0.03 

如果我上運行設備我有:

1: 0.03 
2: 0 

所以基本上設備上的格式化數爲0
我什麼也不是冰是在模擬器上,我得到''作爲小數點分隔符,在設備上我有','。

正因爲如此,它永遠不會得到更多。任何數字,我按它仍然是0.

什麼似乎是問題?

+0

設備vs模擬器上的國際/地區設置是什麼? – Anna 2010-10-26 20:37:32

回答

2

您的設備顯然是設置爲使用,作爲小數點分隔歐洲(或地方)區域。試試行之後加入這一行,你allocinit你的電話號碼格式:

[f setDecimalSeparator:@"."]; 

或者使用setLocale方法(或更改您的設備設置爲語言環境)。

+0

謝謝。有效。在設備上,我用逗號(,)作爲分隔符,這樣(使用setDecimalSeparator)就可以了。 – CristiC 2010-10-26 20:49:27

+0

謝謝*你* - 這是我的第一個iPhone答案。 :) – MusiGenesis 2010-10-26 20:51:21

+0

當我注意到你已經有28.3k的聲望時,我正準備祝賀;)無論如何恭喜! – 2010-10-26 20:59:10

0

試試這樣說:

NSString *currentValue = [textField text]; 
float currentFloat = [currentValue floatValue]; 
NSLog(@"%.2f",currentFloat); //string representation of floatValue 
NSLog(@"%@",currentValue); //string currentValue 
相關問題