1

I'm new to programming. I have a task to make a division of two arbitrary numbers, and to set arbitrary number of decimals. I was searching on the internet, but not really sure how to set it. If I could get some help, would much appreciate!

Here's the code so far:

    int a,b, decimala;
   System.out.println("first number: ");
   a = unos.nextInt();

   System.out.println("second number: ");
   b = unos.nextInt();

   System.out.println("amount of decimals: ");
   decimala = unos.nextInt();

    double c;

    System.out.println(a);
    System.out.println(b);
    System.out.println("--------------");
    c = (double)a/b;
    System.out.println(%.decimala+ c);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Dante983
  • 11
  • 2

1 Answers1

1

If you just want to output them you could try using format

String format = "%" + decimala + "f";
System.out.format(format,a);

Here's a cheat sheet with all the stuff you can do.

https://alvinalexander.com/programming/printf-format-cheat-sheet

Thanks to @AndrewGuerra for pointing out how to format a variable amount of decimals

Nikos Tzianas
  • 633
  • 1
  • 8
  • 21
  • that wouldn`t work, i have a scanner above to choose the amount of decimals – Dante983 Jan 18 '19 at 16:54
  • 1
    In order to form the format string based on the number of decimals specified in your `decimala` variable, you could form the format string by concatenating the variable like so, `"%" + decimala + "f"`, then you can plug this into the format method. – Andrew Guerra Jan 18 '19 at 17:02
  • thanks guys, it helped :D – Dante983 Jan 18 '19 at 17:10