4

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.

2
  • nice question, I was curious too! Commented Mar 25, 2012 at 21:16
  • 1
    Yeahh I know Adel !! I was thinking of it for about 10 minutes and I was not thinking of the concatenation as a solution to it. anyhow problem solved :) Commented Mar 25, 2012 at 21:24

2 Answers 2

6
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 ;)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Andreas, it works and the it is the correct answer.
2

Use:

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

1 Comment

Thank you icyrock for the asnwer!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.