本文介绍了将NSDecimalNumber变为负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种通过乘以 -1 来转换 NSDecimalNumber 为负的方法。

I am looking for a way to turn a NSDecimalNumber negative by multiplying by -1.

/* decNumber is the one I would like to turn negative */
NSDecimalNumber *decNumber = [values objectAtIndex:billIndex];

NSDecimalNumber *minusOne = [[NSDecimalNumber alloc] initWithInt: -1];
finalValue = [[NSDecimalNumber alloc] initWithDecimal: [[decNumber decimalNumberByMultiplyingBy: minusOne] decimalValue]];

这样可行,但感觉这对于这么简单的逻辑来说太过分了。你能想出更好的方法吗?

This works but it feels like it's just too much for such a simple logic. Can you think of a better way to achieve this?

推荐答案

你可以使用更简洁地生成-1。

You could use NSDecimalNumber>>decimalNumberWithMantissa:exponent:isNegative to generate -1 more concisely.

/* Answers (aDecimal x -1) */
NSDecimalNumber* negate(NSDecimalNumber *aDecimal) {
    return [aDecimal decimalNumberByMultiplyingBy:
                    [NSDecimalNumber decimalNumberWithMantissa: 1
                                                      exponent: 0
                                                    isNegative: YES]];
}

这篇关于将NSDecimalNumber变为负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 07:52