本文介绍了NSDecimalNumber 的绝对值 (abs) 没有精度损失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在不损失精度的情况下获得 NSDecimalNumber 的绝对值.我似乎无法找到一种方法来做到这一点而不转换为十进制或浮点数(精度损失).有没有办法做到这一点?

I need to get the absolute value of an NSDecimalNumber without loss of precision. I can't seem to find a way to do this without converting to decimal or float (with a loss of precision). Is there a method to do this?

推荐答案

您可以使用 NSDecimalNumber 类的内置函数将数字与零进行比较,然后根据需要乘以 -1.例如:

You can use the built-in functions of the NSDecimalNumber class to compare the number to zero, then multiply by -1 as appropriate. For example:

- (NSDecimalNumber *)abs:(NSDecimalNumber *)num {
    if ([num compare:[NSDecimalNumber zero]] == NSOrderedAscending) {
        // Number is negative. Multiply by -1
        NSDecimalNumber * negativeOne = [NSDecimalNumber decimalNumberWithMantissa:1
                                                                          exponent:0
                                                                        isNegative:YES];
        return [num decimalNumberByMultiplyingBy:negativeOne];
    } else {
        return num;
    }
}

由于此方法仅适用于 NSDecimalNumbers,因此不会损失精度.

Since this method works solely with NSDecimalNumbers, there's no loss of precision.

这篇关于NSDecimalNumber 的绝对值 (abs) 没有精度损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 22:21