Objective-C - Get the number of decimal places of a double variable

Is there a good way to get the number of decimal places of a double variable in Objective-C? I am struggling to find a way, but without success.

For example, 231.44232000 should return 5.

Thanks in advance.

0


source to share


2 answers


You can multiply by 10 in a loop until the fractional part (returned by modf ()) is close to zero. The number of iterations will be the answer for you. Something like:



int countDigits(double num) {
  int rv = 0;
  const double insignificantDigit = 8;
  double intpart, fracpart;
  fracpart = modf(num, &intpart);
  while ((fabs(fracpart) > 0.000000001f) && (rv < insignificantDigit)) {
    num *= 10;
    rv++;
    fracpart = modf(num, &intpart);
  }

  return rv;
}

      

+3


source


Is there a good way to get the number of decimal places of a double variable in Objective-C?

Not. First, double stores the number in binary, so there might not even be an exact binary representation that matches your decimal. It also doesn't account for the number of significant decimal digits - if that's important, you'll need to track it separately.



You might want to look into NSDecimalNumber if you need to keep the exact representation of the decimal number. You can create your own subclass and add the ability to store and track significant numbers.

+1


source







All Articles