Objective-C - Get number of decimals of a double variable

自古美人都是妖i 提交于 2019-12-11 19:56:55

问题


Is there a nice way to get the number of decimals of a double variable in Objective-C? I am struggling for a while to find a way but with no success.

For example 231.44232000 should return 5.

Thanks in advance.


回答1:


You could, in a loop, multiply by 10 until the fractional part (returned by modf()) is really close to zero. The number of iterations'll be the answer you're after. 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;
}



回答2:


Is there a nice way to get the number of decimals of a double variable in Objective-C?

No. For starters, a double stores a number in binary, so there may not even be an exact binary representation that corresponds to your decimal number. There's also no consideration for the number of significant decimal digits -- if that's important, you'll need to track it separately.

You might want to look into using NSDecimalNumber if you need to store an exact representation of a decimal number. You could create your own subclass and add the ability to store and track significant digits.



来源:https://stackoverflow.com/questions/8290385/objective-c-get-number-of-decimals-of-a-double-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!