-1

I want to format my decimal number output, so that it has N amount of decimal space.

For certain amount of places I know you can just do

System.out.printf("%.2f",number);

but I want to do something like

System.out.printf("%.(%d)f",spaces,number);

So basically the same output but the number of decimal space changes based on the input (the user determines amount of decimal space). I understand that line doesn't work but I don't know other ways to do this.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

0

Try it like this.

  • % escapes % so %% formats a single %.
  • formatted does the same thing as String.format()
  • After formatted is done, the format string will be %.2f%n
int n = 2;
double value = 3.88833; 

System.out.printf("%%.%df%n".formatted(n), value);

prints

3.89
WJS
  • 36,363
  • 4
  • 24
  • 39