2010-10-26 117 views
35

我讀thisthat。我想這恰好:限制一個雙精度到小數點後兩位的小數位

1.4324 => 「1.43」
9.4000 => 「9.4」
43.000 => 「43」

9.4 => 「9.40」(錯誤)
43.000 = >「43.00」(錯誤)

在兩個問題中,答案均指向NSNumberFormatter。所以它應該很容易實現,但不適合我。

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 20)]; 

    NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init]; 
    [doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle]; 
    [doubleValueWithMaxTwoDecimalPlaces setPaddingPosition:NSNumberFormatterPadAfterSuffix]; 
    [doubleValueWithMaxTwoDecimalPlaces setFormatWidth:2]; 

    NSNumber *myValue = [NSNumber numberWithDouble:0.]; 
    //NSNumber *myValue = [NSNumber numberWithDouble:0.1]; 

    myLabel.text = [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]; 

    [self.view addSubview:myLabel]; 
    [myLabel release]; 
    myLabel = nil; 
    [doubleValueWithMaxTwoDecimalPlaces release]; 
    doubleValueWithMaxTwoDecimalPlaces = nil; 
} 

我也

NSString *resultString = [NSString stringWithFormat: @"%.2lf", [myValue doubleValue]]; 
NSLog(@"%@", resultString); 

所以試了一下我怎麼能以最大的兩位小數格式化雙重價值?如果最後一個位置包含一個零,則應該省略零。

解決方案:

NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init]; 
[doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle]; 
[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2]; 
NSNumber *myValue = [NSNumber numberWithDouble:0.]; 
NSLog(@"%@",[doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]]; 
[doubleValueWithMaxTwoDecimalPlaces release]; 
doubleValueWithMaxTwoDecimalPlaces = nil; 
+0

你想四捨五入嗎?那應該是1.4363 =>「1.43」或「1.44」? – 2010-10-26 17:48:50

+0

我認爲這是有道理的。 – testing 2010-10-26 17:50:44

+0

畢竟不要忘了發佈doubleValueWithMaxTwoDecimalPlaces ... – Lukasz 2010-12-15 22:23:35

回答

41

嘗試添加以下行,配置您的格式化時:

[doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2]; 
0

如何從字符串?:

結束脩剪不想要的字符
NSString* CWDoubleToStringWithMax2Decimals(double d) { 
    NSString* s = [NSString stringWithFormat:@"%.2f", d]; 
    NSCharacterSet* cs = [NSCharacterSet characterSetWithCharacterInString:@"0."]; 
    NSRange r = [s rangeOfCharacterInSet:cs 
           options:NSBackwardsSearch | NSAnchoredSearch]; 
    if (r.location != NSNotFound) { 
     s = [s substringToIndex:r.location]; 
    } 
    return s; 
} 
+1

儘管此解決方案有效,但還有更好的解決方案(請參閱接受的答案) – Muxa 2015-02-10 01:02:43

0
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; 
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown]; 
[numberFormatter setMinimumFractionDigits:2]; 
numberFormatter.positiveFormat = @"0.##"; 
NSNumber *num = @(total_Value); 
+0

pl解釋您的答案 – 2017-04-10 10:55:50

+0

@SahilMittal以上代碼NSNumberFormatterRoundDown返回無輪值,則positiveFormat僅給出兩個小數點值。 – 2017-04-11 07:12:46

相關問題