2014-01-31 42 views
0

我有一個字符串表示一個浮點數,例如2400.0。我想將其格式化爲數字(2,400.0),我需要在數字符號後面保留零。NSNumberFormatter:顯示0作爲最後一個數字,從像25.0這樣的字符串開始

NSString* theString = @"2400.0"; 

// I convert the string to a float 
float f = [theString floatValue]; 
// here I lose the digit information :(and it ends up with 2400 instead of 2400.0 

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
[formatter setUsesSignificantDigits:YES]; 
[formatter setMinimumFractionDigits:1]; 
[formatter setMaximumFractionDigits:2]; 
[formatter setLocale:[NSLocale currentLocale]]; 

NSString *result = [formatter stringFromNumber:@(f)]; 

的的resultNSLog2,400,而我需要2,400.0

我怎樣才能獲得正確的字符串?

回答

3

您可能想要將minimumFractionDigits設置爲1(以及您的maximumFractionDigits也是這種情況)。

你也可能不想使用有效數字。下面的代碼產生所需的輸出:

NSString *theString = @"2400.0"; 

float f = [theString floatValue]; 

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
[formatter setMinimumFractionDigits:1]; 
[formatter setMaximumFractionDigits:1]; 
[formatter setLocale:[NSLocale currentLocale]]; 

NSLog(@"%@", [formatter stringFromNumber:@(f)]); 
+0

的問題是,從字符串的第一個轉換過程中漂浮我失去了」 .0" 的信息。我已經嘗試設置'minimumFractionDigits'。順便說一句我把它添加到我的代碼示例更加精確。 – MatterGoal

+0

我不明白你如何失去'.0'(我能理解的另一個分數,但'.0'?)無論如何,你需要兩個數字格式化器:一個用於輸入,另一個用於輸出。 – DarkDust

+0

哦,既然你設置了'setUsesSignificantDigits:YES',你可能需要設置['minimumSignificantDigits'](https://developer.apple.com/library/mac/documentation/cocoa/reference/Foundation/Classes/NSNumberFormatter_Class/ Reference/Reference.html#// apple_ref/occ/instm/NSNumberFormatter/setMinimumSignificantDigits :)(參見[this question](http://stackoverflow.com/questions/1322348/what-describes-nsnumberformatter-maximumsignificantdigits))或把它們關掉。 – DarkDust

0

下面解決問題

NSString *formatString = @"0,000.0"; 
[formatter setPositiveFormat:formatString]; 

將被用於格式化0的小數後的數字。它也適用於負數。

您應該根據小數點前後浮點數的位數動態更改格式字符串。

希望它有幫助。

+1

我需要保留區域設置信息。這不是一個解決方案。許多國家使用不同的格式,如'@「0.000,0」' – MatterGoal

+0

同意,這不是一個通用的解決方案。然而,它提供了問題「需要一個格式爲0,000.0」的通用解決方案,我們需要設置區域設置爲格式化程序。 –

0

容易,

然後你去顯示它只是這樣做:

myLabel.text = @"%0.1f", f; 
相關問題