【问题标题】:Change the decimal places by number from variable - JAVA [duplicate]从变量中按数字更改小数位 - JAVA [重复]
【发布时间】:2020-02-29 17:08:11
【问题描述】:

我需要用字符串格式对数字进行四舍五入。喜欢:

String output = String.format("%.10d",var); 

但要注意的是小数位数取自变量,该变量由用户从控制器设置。

我需要帮助重写它,10 是我的小数位数变量。但我被困住了。

有什么想法吗?谢谢

【问题讨论】:

标签: java variables formatting number-formatting


【解决方案1】:

动态构建格式字符串:

double value = 12345.67890123456;
for (int decimals = 0; decimals <= 10; decimals++) {
    String output = String.format("%." + decimals + "f", value);
    System.out.println(output);
}

输出

12346
12345.7
12345.68
12345.679
12345.6789
12345.67890
12345.678901
12345.6789012
12345.67890123
12345.678901235
12345.6789012346

或者,使用DecimalFormat:

double value = 12345.67890123456;
DecimalFormat fmt = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.US));
for (int decimals = 0; decimals <= 10; decimals++) {
    fmt.setMinimumFractionDigits(decimals);
    fmt.setMaximumFractionDigits(decimals);
    String output = fmt.format(value);
    System.out.println(output);
}

与上面的输出相同。

如您所见,它们都四舍五入到最接近的位置(也就是一半)。


如果要四舍五入,必须使用DecimalFormat,并在循环前添加这一行更改默认RoundingMode:

fmt.setRoundingMode(RoundingMode.UP);

输出

12346
12345.7
12345.68
12345.679
12345.6790
12345.67891
12345.678902
12345.6789013
12345.67890124
12345.678901235
12345.6789012346

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2014-09-28
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多