Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting a string in java

Tags:

java

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

i have a code written as follows

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

addNumbers.numberRepresentaiton(int precision);

The method is defined as below

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

executing the above results in conversion formatting error. Thank you for your time.

like image 862
Sinan Avatar asked Feb 21 '23 01:02

Sinan


2 Answers

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

You have to concatenate the format string - the Formatter can't detect the variable name automagically ;)

like image 173
Andreas Dolk Avatar answered Feb 23 '23 13:02

Andreas Dolk


Use:

return String.format("%." + precision + "f", add);
like image 44
icyrock.com Avatar answered Feb 23 '23 14:02

icyrock.com