String formatting in java

I would like to know how to provide formatting capabilities that allow the user to specify the number of digits accurate to a decimal number. so instead of using the classic formatting .2f or .3f, etc. I want the user to be able to enter decimal precision.

I have code written as follows

Scanner input = new Scanner (System.in); int precision = input.nextInt(); addNumbers.numberRepresentaiton(int precision); 

The method is defined below:

 private String numberRepresentation(int precision) { return String.format("%.precisionf", add); } 

execution of the above results with a conversion formatting error. Thank you for your time.

+4
source share
2 answers
 private String numberRepresentation(int precision) { return String.format("%." + precision + "f", add); } 

You must concatenate the format string - Formatter cannot automatically determine the variable name;)

+6
source

Using:

 return String.format("%." + precision + "f", add); 
+2
source

Source: https://habr.com/ru/post/1403352/


All Articles