Search code examples
iosobjective-cmathnsnumber

how to compare double number with 30 decimal places with the highest precision?


i need to compare two big decimal number with 30 decimal places. I need to detect a difference also in the 30th decimal place, so in my needs this:

double number_1=80.004752165027610999459284357728;
double number_2=80.004752165027610999459284357727;

leads into this:

double result = 0.000000000000000000000000000001

It seems to be impossible due the nature itself of the number (i have tried with float,long double) . I have only a limited set of decimal places to operate. So in that case how i can achive a better precision? Maybe i can use some framework's function ? I haven't found nothing useful in nsnumber and in google


Solution

  • You can use NSDecimalNumber. It should work with up to 38 digits.

    NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.

    Documentation