2010-10-26 116 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