rottendevice
rottendevice

Reputation: 2879

Absolute value isn't working

My iPhone has a line of code that looks like this:

double decimal2 = abs(newLocation.coordinate.longitude - degrees);

I'm trying to ensure that the value of decimal2 is always positive. However, decimal2 is currently -82.

Can anyone explain this? I'm not doing anything else to the value of decimal2.

Thanks.

Upvotes: 1

Views: 976

Answers (3)

Caleb
Caleb

Reputation: 124997

You're using the abs() function, which returns int, but assigning the result to a double. You should either assign the result to a variable of type int, or use a version of the absolute value function that returns double: double fabs(double).

Upvotes: 2

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

would suggest you to use NSDecimalNumber

You could 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 [myNumber 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;
    }
}

in this case , there's no loss of precision

Upvotes: 4

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

Perhaps this "abs" function isn't what you think it is. Are you sure you know where it's coming from? Maybe you or someone else has defined your own? There's no reason why a valid "abs" function would do this.

Upvotes: 2

Related Questions