问题
When writing the code, one of the tasks was to allow the user to change the decimal format within the entire program.
The program consists of multiple calculators, all of them should be able to give decimal results. The user has then a choice of how many decimal places they would like to see.
I know this can be done with format options just not sure how.
/Answer given already
回答1:
Create a variable containing a DecimalFormat
DecimalFormat df = new DecimalFormat();
In menu option 4 where number of decimals is selected and read into dec
df.setMaximumFractionDigits(dec);
df.setMinimumFractionDigits(dec);
The above means that numbers will always be printed with dec
number of decimals
Then whenever you want to print a double use the formatter
System.out.println("The result is " + df.format(someValue));
An example
DecimalFormat df = new DecimalFormat();
for (int i = 0; i < 4; i++) {
df.setMaximumFractionDigits(i);
df.setMinimumFractionDigits(i);
System.out.println("example " + df.format(24) + " " + df.format(12.3456));
}
outputs
example 24 12
example 24.0 12.3
example 24.00 12.35
example 24.000 12.346
回答2:
Try java method: String.format();
double number = 12.43544545;
int decimalPoint = 3;
System.out.println(String.format("%." + decimalPoint + "f", number));
来源:https://stackoverflow.com/questions/54402352/changing-a-decimal-format-within-the-entire-code-using-an-option-created-in-a-sw