C# get digits from float variable

前端 未结 12 1681
南笙
南笙 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:11

    To suggest something different than the others, an extension method (with a method similar to David's):

    public static int GetDecimalAsInt(this float num)
    {
        string s = n.ToString();
        int separator = s.IndexOf(System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator);
        return int.Parse(s.Substring(separator + 1));
    }
    
    // Usage:
    float pi = 3.14;
    int digits = pi.GetDecimalAsInt();
    

    Edit: I didn't use the "best" answer, because it omitted the hardest part, which is converting an arbitrary decimal number, and did not work for negative numbers. I added the correction requested in David's answer.

提交回复
热议问题