-1
    public class Main {
        public static void main(String[] args) {

           Scanner scanner = new Scanner(System.in);

           long number = 0;
           String userInput;
           boolean var = false;

           System.out.print("Enter a number: ");
           while (!var) {
               try {
                   userInput  = scanner.nextLine();
                   number = Long.parseLong(userInput);
                   if (number < 0) {
                       System.out.print("You should enter a number greater than or equal to zero!\n" +
                        "Please try again: ");
                   } else {
                       var = true;
                   }
              } catch (NumberFormatException e) {
                  System.out.print("Error - You should enter a number!\nPlease try again: ");
        }
    }


          BigInteger prod = BigInteger.ONE;
          for (int i = 1; i <= number; i++) {
             prod = prod.multiply(BigInteger.valueOf(i));
    }
          System.out.println(number + "! = " + prod);


}



  }

I have this program for showing the factorial of a given number. It works fine but there is something that bothers me, I want to display very long numbers like this "1.551121004×10^25". Is there a method in java, or something else that I can use?

  • 1
    Does this answer your question? [Format double value in scientific notation](https://stackoverflow.com/questions/2944822/format-double-value-in-scientific-notation) – dan1st Sep 18 '21 at 08:37
  • @dan1st , it does a bit, but I want to format like this only for very large numbers like 10M and so on – Alex Darius Sep 18 '21 at 08:55
  • @AlexDarius if you convert to a BigDecimal you can use toEngineeringString. Still not quite right and in both cases (double and BigDecimal) you might lose the exactness of the BigInteger in the output. When you compute factorials you don't want approximations, right? – ewramner Sep 18 '21 at 08:59
  • You can just use an `if`-condition in order to seperate between large numbers and normal numbers. – dan1st Sep 18 '21 at 09:03
  • @dan1st , I did it like that and it seems that it works – Alex Darius Sep 18 '21 at 09:08

1 Answers1

0

Java's java.text.DecimalFormat#DecimalFormat(java.lang.String) is a useful method to format numbers, you can do like this:

        BigInteger    bigInteger    = new BigInteger("1222222222");
        DecimalFormat decimalFormat = new DecimalFormat("0.##E0");
        String        formatStr     = decimalFormat.format(bigInteger);
        System.out.println(formatStr);

For this case, the result is 1.22E9, whether I'm not sure this satisfy your demand.

And maybe you can change the format code 0.##E0 to make the result like 1.551121004×10^25