我有一個字符串表示一個浮點數,例如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)];
的的result
NSLog
是2,400
,而我需要2,400.0
我怎樣才能獲得正確的字符串?
的問題是,從字符串的第一個轉換過程中漂浮我失去了」 .0" 的信息。我已經嘗試設置'minimumFractionDigits'。順便說一句我把它添加到我的代碼示例更加精確。 – MatterGoal
我不明白你如何失去'.0'(我能理解的另一個分數,但'.0'?)無論如何,你需要兩個數字格式化器:一個用於輸入,另一個用於輸出。 – DarkDust
哦,既然你設置了'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