Check if a number is a double or an int

后端 未结 5 2072
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 11:49

I am trying to beautify a program by displaying 1.2 if it is 1.2 and 1 if it is 1 problem is I have stored the numbers into the arraylist as doubles. How can I check if a Number

5条回答
  •  再見小時候
    2021-02-06 12:07

    I am C# programmer so I tested this in .Net. This should work in Java too (other than the lines that use the Console class to display the output.

    class Program
    {
        static void Main(string[] args)
        {
            double[] values = { 1.0, 3.5, 123.4567, 10.0, 1.0000000003 };
            int num = 0;
            for (int i = 0; i < values.Length; i++ )
            {
                num = (int) values[i];
                // compare the difference against a very small number to handle 
                // issues due floating point processor
                if (Math.Abs(values[i] - (double) num) < 0.00000000001)
                {
                    Console.WriteLine(num);
                }
                else // print as double
                {
                    Console.WriteLine(values[i]);
                }
            }
            Console.Read();
        }
    }
    

提交回复
热议问题