C# 查找 Double 的小数点后的位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9386672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:09:17  来源:igfitidea点击:

Finding the number of places after the decimal point of a Double

c#

提问by blitzkriegz

I have a Double value:

我有一个双值:

double a = 4.5565;

What is the easiest way to calculate the number of digits after the decimal point (4 in this case).

计算小数点后位数的最简单方法是什么(在这种情况下为 4)。

I know that I can convert to string and do a split and take the length. But is there an easier way?

我知道我可以转换为字符串并进行拆分并取长度。但是有没有更简单的方法呢?

采纳答案by phoog

There's no easy way, especially since the number of digits mathematically speaking might be far more than displayed. For example, 4.5565 is actually stored as 4.556499999999999772626324556767940521240234375(thanks to haroldfor calculating that). You're very unlikely to find a useful solution to this problem.

没有简单的方法,特别是因为从数学上讲,数字的数量可能远远超过显示的数量。例如,4.5565 实际上存储为4.556499999999999772626324556767940521240234375(感谢harold计算)。您不太可能找到解决此问题的有用解决方案。

EDIT

编辑

You couldcome up with some algorithm that works like this: if, as you calculate the decimal representation, you find a certain number of 9s (or zeros) in succession, you round up (or down) to the last place before the series of 9s (or zeros) began. I suspect that you would find more trouble down that road than you would anticipate.

可以想出一些像这样工作的算法:如果在计算十进制表示时,你发现连续的一定数量的 9(或零),你向上(或向下)四舍五入到系列之前的最后一位9s(或0s)开始。我怀疑在这条路上你会发现比你预期的更多的麻烦。

回答by james

I Think String solution is best : ((a-(int)a)+"").length-2

我认为字符串解决方案是最好的: ((a-(int)a)+"").length-2

回答by KeithS

var precision = 0;
var x = 1.345678901m;

while (x*(decimal)Math.Pow(10,precision) != 
         Math.Round(x*(decimal)Math.Pow(10,precision))) 
   precision++;

precisionwill be equal to the number of significant digits of the decimal value (setting x to 1.23456000 will result in a precision of 5 even though 8 digits were originally specified in the literal). This executes in time proportional to the number of decimal places. It counts the number of fractional digits ONLY; you can count the number of places to the left of the decimal point by taking the integer part of Math.Log10(x). It works best with decimals as they have better value precision so there is less rounding error.

precision将等于十进制值的有效位数(将 x 设置为 1.23456000 将导致精度为 5,即使最初在文字中指定了 8 位数字)。这按与小数位数成比例的时间执行。它只计算小数位数;您可以通过取 Math.Log10(x) 的整数部分来计算小数点左边的位数。它最适合小数,因为它们具有更好的值精度,因此舍入误差更小。

回答by user1996255

Write a function

写一个函数

int CountDigitsAfterDecimal(double value)
        {
            bool start = false;
            int count = 0;
            foreach (var s in value.ToString())
            {
                if (s == '.')
                {
                    start = true;
                }
                else if (start)
                {
                    count++;
                }
            }

            return count;
        }

回答by Nikhil Girraj

I'll perhaps use this code if I needed,

如果需要,我可能会使用此代码,

myDoubleNumber.ToString("R").Split('.')[1].Length

"R"here is Round Trip Format Specifier

"R"这是往返格式说明符

We need to check for the index bounds first of course.

当然,我们首先需要检查索引边界。

回答by Koray

I think this might be a solution:

我认为这可能是一个解决方案:

 private static int getDecimalCount(double val)
 {
     int i=0;
     while (Math.Round(val, i) != val)
         i++;
     return i;
 }

double val9 = 4.5565d; int count9 = getDecimalCount(val9);//result: 4

Sorry for the duplication -> https://stackoverflow.com/a/35238462/1266873

抱歉重复 -> https://stackoverflow.com/a/35238462/1266873

回答by batsheva

base on james answer bat much clearer:

基于詹姆斯回答蝙蝠更清楚:

int num = dValue.ToString().Length - (((int)dValue).ToString().Length + 1);

num is the exact number of digits after the decimal point. without including 0 like this(25.520000) in this case, you will get num= 2

num 是小数点后的确切位数。在这种情况下,如果不包括这样的 0(25.52 0000),您将得到 num=2

回答by RooiWillie

Another solution would be to use some string functions:

另一种解决方案是使用一些字符串函数:

private int GetSignificantDecimalPlaces(decimal number, bool trimTrailingZeros = true)
{
  string stemp = Convert.ToString(number);

  if (trimTrailingZeros)
    stemp = stemp.TrimEnd('0');

  return stemp.Length - 1 - stemp.IndexOf(
     Application.CurrentCulture.NumberFormat.NumberDecimalSeparator);
}

Remember to use System.Windows.Forms to get access to Application.CurrentCulture

请记住使用 System.Windows.Forms 来访问 Application.CurrentCulture