3

我想格式化像 45.50 这样的价格,但我不想要像 45.00 这样的价格。我怎样才能避免这种情况?

4

5 回答 5

4

我是这样做的:

NSNumber *amount = @(50.5);
NSNumberFormatter *currencyFormat = [[NSNumberFormatter alloc] init];
[currencyFormat setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormat setLocale:[NSLocale currentLocale]];

if (trunc(amount.floatValue) == amount.floatValue) {
    [currencyFormat setMaximumFractionDigits:0];
} else {
    [currencyFormat setMaximumFractionDigits:2];
}

NSLog(@"%@", [currencyFormat stringFromNumber:amount]);

我喜欢这个解决方案的简单性。输出将是$50.50. 而对于amount = @(50.0)将是$50

于 2014-02-25T08:34:15.607 回答
1

如果你只是在一个非常快速和肮脏的黑客之后。. .

// Get the price as a string
NSString *priceString = [NSString stringWithFormat:@"%2.2f", priceFloat];

// Trim if needed
if ([priceString hasSuffix:@".00"])
    priceString = [priceString substringToIndex:priceString.length-3];

注意 此方法不适用于本地化内容,即在欧洲,小数点分隔符是逗号,因此您将看到 45,00,而不是 45.00。

于 2012-09-04T12:31:35.593 回答
1

做这个:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:22.368511]];
NSLog(@"Result...%@",numberString);//Result 22.37

现在像这样跟踪不需要的:

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;
}
于 2012-09-04T12:08:06.743 回答
0
float myOriginalPrice = 45.50;
    CGFloat mod = fmod(myOriginalPrice, 1);
    if (mod == 0){
        mod = (int)myOriginalPrice;
        NSLog(@"%.0f", mod);


    } else {
         NSLog(@"%f", myOriginalPrice);
    }
于 2012-09-04T12:08:41.303 回答
0
  INPUT : 12.74 OR 12.745

NSString *inputString=[NSString string];


inputString=[NSString stringWithFormat:@"%.4g",12.74f];


NSLog(@"inputString : %@ \n\n",inputString);

输出:

  inputString : 12.74 
INPUT : 12.00 OR 12.000

  NSString *inputString=[NSString string];


 inputString=[NSString stringWithFormat:@"%.4g",12.00f];


 NSLog(@"inputString : %@ \n\n",inputString);

输出:

inputString:12 更新答案:对于他的评论问题

输入:12.30

我在这里假设他将在一些 UI 中显示这个值,比如 UILabel,......不是为了计算。

 NSString *inputString=[NSString string];


 inputString=[NSString stringWithFormat:@"%.4g",12.30f];


 NSArray *arr=[inputString componentsSeparatedByString:@"."];


 if ([arr count] >= 2) {

    NSString *secondStr=[arr objectAtIndex:1];

if ([secondStr length]<2) {

    inputString=[NSString stringWithFormat:@"%@0",inputString];
}
}

NSLog(@"inputString : %@ \n\n",inputString); 输出:

输入字符串:12.30

于 2012-09-04T12:13:16.063 回答