在不丢失小数部分的情况下否定 NSDecimalNumber

Negate an NSDecimalNumber without losing the fractional part

我正在使用这段代码来反转 NSDecimalNumber 以便于计算:

    self.thisTransaction.amount = [NSDecimalNumber decimalNumberWithString:self.amountField.text locale:NSLocale.currentLocale];

    NSLog(@"1 thisTransaction.amount is %@",self.thisTransaction.amount);

    // Inverts the transaction amount

    // This code negates the number, but chops off the part on the right side of the decimal

    self.thisTransaction.amount = [NSDecimalNumber decimalNumberWithMantissa:[self.thisTransaction.amount longLongValue] exponent:0 isNegative:YES];

    NSLog(@"2 thisTransaction.amount is %@",self.thisTransaction.amount);

好吧,无论如何,我认为算术会更容易。然而,如下面的控制台读数所示,代码取反了数字,但截断了小数点的数字,returns 一个整数而不是小数:

2015-05-27 10:07:30.767 XXXXX[11835:10266658] 1 thisTransaction.amount is 25.49
2015-05-27 10:07:39.735 XXXXX[11835:10266658] 2 thisTransaction.amount is -25

我看了很多关于 SO 的帖子,但它们似乎在兜圈子。我非常感谢您的指导。

编辑:

根据下面@rmaddy的建议,我修改了代码如下:

    self.thisTransaction.amount = [NSDecimalNumber decimalNumberWithString:self.amountField.text locale:NSLocale.currentLocale];

    NSLog(@"1 thisTransaction.amount is %@",self.thisTransaction.amount);

    // Inverts the transaction amount

    NSDecimalNumber * invertedMultiplier = [NSDecimalNumber decimalNumberWithString:@"-1"];

    self.thisTransaction.amount = [self.thisTransaction.amount decimalNumberByMultiplyingBy:invertedMultiplier];



    NSLog(@"2 thisTransaction.amount is %@",self.thisTransaction.amount);

这似乎工作正常。

如果你想否定一个 NSDecimalNumber 你可以简单地做:

NSDecimalNumber *originalNumber = ... // the original decimal number

NSDecimalNumber *negatedNumber = [originalNumber decimalNumberByMultiplyingBy:[NSDecimalNumber numberWithInt:-1]];

为了好玩,还有另一种方式:

NSDecimalNumber *anotherNegate = [[NSDecimalNumber zero] decimalNumberBySubtracting:originalNumber];