Get the decimal part from a double

后端 未结 18 886
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 06:47

I want to receive the number after the decimal dot in the form of an integer. For example, only 05 from 1.05 or from 2.50 only 50 not 0.50

18条回答
  •  鱼传尺愫
    2020-11-29 07:28

    Here's an extension method I wrote for a similar situation. My application would receive numbers in the format of 2.3 or 3.11 where the integer component of the number represented years and the fractional component represented months.

    // Sample Usage
    int years, months;
    double test1 = 2.11;
    test1.Split(out years, out months);
    // years = 2 and months = 11
    
    public static class DoubleExtensions
    {
        public static void Split(this double number, out int years, out int months)
        {
            years = Convert.ToInt32(Math.Truncate(number));
    
            double tempMonths = Math.Round(number - years, 2);
            while ((tempMonths - Math.Floor(tempMonths)) > 0 && tempMonths != 0) tempMonths *= 10;
            months = Convert.ToInt32(tempMonths);
        }
    }
    

提交回复
热议问题