Changing a decimal format within the entire code using an option created in a switch menu

我的梦境 提交于 2019-12-24 21:26:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!