C# get digits from float variable

前端 未结 12 1677
南笙
南笙 2020-12-06 16:26

I have a float variable and would like to get only the part after the comma, so if I have 3.14. I would like to get 14 as an integer. How can I do that?

12条回答
  •  盖世英雄少女心
    2020-12-06 17:19

    Here's another version that also tells how many digits are part of the fractional make-up, which I needed.

    public static int GetFractionalPartAsInt(decimal n, out int numOfFractionalDigits)
    {
      n -= Math.Truncate(n);
      n = Math.Abs(n);
    
      int numOfFractionalDigitsValue = 0;
      // When n != Math.Truncate(n), we have seen all fractional decimals.
      while (n != Math.Truncate(n))
      {
        n *= 10;
        numOfFractionalDigitsValue++;
      }
    
      numOfFractionalDigits = numOfFractionalDigitsValue;
    
      return (int)n;
    }
    

    It's similar in idea to David's answer (his non-cheating version). However, I used the decimal type instead of double, which slows things down, but improves accuracy. If I convert David's (again, non-cheating version) answer to use a decimal type (in which case his "precision" variable can be changed to the constant zero), my answer runs about 25% faster. Note that I also changed his code to provide the number of fractional digits in my testing.

提交回复
热议问题