我想格式化价格如45.50,但我不希望价格像45.00。我怎么能避免这个?
答案 0 :(得分: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
答案 1 :(得分: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;
}
答案 2 :(得分:1)
float myOriginalPrice = 45.50;
CGFloat mod = fmod(myOriginalPrice, 1);
if (mod == 0){
mod = (int)myOriginalPrice;
NSLog(@"%.0f", mod);
} else {
NSLog(@"%f", myOriginalPrice);
}
答案 3 :(得分: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 更新的答案:对于他的评论问题
INPUT: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); 输出:
inputString:12.30
答案 4 :(得分:0)
如果你只是在一个非常快速和肮脏的黑客之后。 。
// 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。