0
import java.util.*;
// Algorithm and Java program to find a Factorial of a number using recursion

public class factorial {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a number: ");

        int n = input.nextInt();
        System.out.println("The factorial of " + n + " is " + factorial(n));

    }

    private  static double factorial (int n)
    {
        if (n == 1)
            return 1;
        else
            return n * factorial(n - 1);
    }
}

Please enter a number: 8 The factorial of 8 is 40320.0

Process finished with exit code 0 How to get a whole number without decimal?

Zac
  • 1,719
  • 3
  • 27
  • 48
j007
  • 11
  • 2
  • 3
    Why do you switch from an `int` to a `double` if you only want a whole number? – GBlodgett Sep 05 '18 at 00:54
  • change your code to only deal with `int` variables. – Scary Wombat Sep 05 '18 at 01:04
  • 2
    Possible duplicate of [How to nicely format floating numbers to String without unnecessary decimal 0?](https://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0) – Patrick Parker Sep 05 '18 at 01:10

2 Answers2

1

You can get the int Value or Double Value by calling:

Double n = new Double(40320.99);
int i = n.intValue();

You can directly print the result whatever it's int or Double Value data type.

RogerSK
  • 393
  • 1
  • 18
0

Replace

System.out.println("The factorial of " + n + " is " + factorial(n));

by

System.out.println("The factorial of " + n + " is " + (int) factorial(n));

OR (better way)

Replace

private static double factorial (int n)

by

private static int factorial(int n)


Explanation

Since your method is returning a double, you need to convert it to an int, which does not have decimal places. You might want to look at methods of the Math class like round(), floor(), etc.

Kartik
  • 7,677
  • 4
  • 28
  • 50