Absolute Value (abs) of NSDecimalNumber without loss of precision

前端 未结 4 1302
情书的邮戳
情书的邮戳 2020-12-31 00:35

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

4条回答
  •  说谎
    说谎 (楼主)
    2020-12-31 01:16

    If you do not want to multiply it, zero subtracting the value will do the trick.

    - (NSDecimalNumber *)abs:(NSDecimalNumber *)num {
        if ([num compare:[NSDecimalNumber zero]] == NSOrderedAscending) {
            // negative value
            return [[NSDecimalNumber zero] decimalNumberBySubtracting:num];
        } else {
            return num;
        }
    }
    

提交回复
热议问题