Search code examples
javaif-statementdoublecalculator

Only return a decimal if it's not a whole number


I've been trying to write a function isWhole that is given a double and looks to see if it's a whole number, and if it is return the value without the decimal (as an int?) else return it with 3 decimal places (I can do this part with number format.

My question is how can I check if a double is a whole number and even a recursive decimal?


Solution

  • [UPDATE] returns value - with 3 decimal places

    public boolean isWhole(double value) {
        return Math.floor(value) == value;
    }
    
    • You can't have a function that returns either int or double
    • To convert double to int; simply typecast :- int valueInt = (int) valueDouble;