1

I have trouble when I have currency value

999999999999999999.99

From that value, I want to display it as String. The problem is that value always rounded to

1000000000000000000.00

I'm not expect that value rounded. I want the original value displayed. Do you have any idea how to solve this problem? I tried this code from some answer/turorial in stackoverflow.com :

NSMutableString *aString = [NSMutableString stringWithCapacity:30];

NSNumberFormatter *aCurrency = [[NSNumberFormatter alloc]init];
[aCurrency setFormatterBehavior:NSNumberFormatterBehavior10_4];
[aCurrency setNumberStyle:NSNumberFormatterCurrencyStyle];   
[aCurrency setMinimumFractionDigits:2];
[aCurrency setMaximumFractionDigits:2];
[aString appendString:[aCurrency stringFromNumber:productPrice]];
//productPrice is NSDecimalNumber which is have value 999999999999999999.99

cell.textLabel.text = aString;
NSLog(@"the price = %@",cell.textLabel.text);
//it prints $1,000,000,000,000,000,000.00
[aCurrency release];
4

2 回答 2

4

除非您有充分的理由不这样做,否则通常最好将货币值保持为定点格式,而不是浮点数。Ada 直接支持这一点,但对于 C-ish 语言,您所做的是以pennies为单位而不是美元,并且只在您显示它时进行转换。

所以在这种情况下,productPrice 的值将是 99999999999999999999(美分)。要显示它,你会做这样的事情(如果这是 C。我不懂语言):

int const modulus = productPrice % 100;
printf ("The price = %d.%d\n", (int) ((productPrice - modulus) / 100), modulus);

我还会使用整数而不是浮点变量来保持几乎所有情况下的值。在这种情况下它不起作用(即使您使用 64 位整数),因为您的值大得令人难以置信。我们说的是美国国债的 100 万倍如果这么大的美元价值对我一生中的任何事情都有意义,那么我们都遇到了大麻烦。

于 2010-02-05T13:52:46.700 回答
0

Have you tried these:

* – setRoundingBehavior:
* – roundingBehavior
* – setRoundingIncrement:
* – roundingIncrement
* – setRoundingMode:
* – roundingMode
于 2010-02-05T13:43:04.580 回答