C# get digits from float variable

前端 未结 12 1678
南笙
南笙 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

    The cheating way to do it is:

        private Int32 FractionalPart(double n)
        {
            string s = n.ToString("#.#########", System.Globalization.CultureInfo.InvariantCulture);
            return Int32.Parse(s.Substring(s.IndexOf(".") + 1));
        }
    

    edit2: OK OK OK OK. Here is the most paranoid never fail version I can come up with. This will return the first 9 digits (or less, if there aren't that many) of the decimal portion of the floating point number. This is guaranteed to not overflow an Int32. We use the invariant culture so we know that we can use a period as the decimal separator.

提交回复
热议问题