简体   繁体   English

Java使用DecimalFormat进行奇怪的舍入

[英]Java strange rounding with DecimalFormat

double number = Scanner.nextDouble();    
DecimalFormat df = new DecimalFormat("#.#");
        System.out.print (df.format(number));

I've tried the above for rounding my number to 1 decimal place but in cases where there are no decimal numbers, it seems to round to an integer value (for example 2.0 would be displayed as 2). 我已经尝试过将上面的数字四舍五入到小数点后1位,但是在没有十进制数的情况下,它似乎舍入为整数值(例如2.0将显示为2)。 I want 2.0, as well as any other input number to display in 1 decimal place. 我想要2.0,以及任何其他输入数字以1位小数显示。 Also, when DecimalFormat rounds a negative number to 0, it turns it to -0. 此外,当DecimalFormat将负数舍入为0时,它会将其变为-0。 How can I solve these issues? 我该如何解决这些问题?

Use "0.0" as your format string. 使用“0.0”作为格式字符串。 # means a digit, or blank if zero which is what you're seeing. #表示数字,如果为零则为空白,这就是您所看到的。

For getting rid of the sign, take a look at this answer . 为了摆脱这个标志,看看这个答案

There is nothing strange about the output. 输出没什么奇怪的。 The format is just not as per your requirement. 格式不符合您的要求。

In DecimalFormat # will only output the character in its specified decimal place if it makes sense. DecimalFormat #只会输出在其指定的小数位数的字符,如果它是有道理的。 So 10.00 will simply be 10. If you want decimal places to be significant you need to use 0 . 所以10.00将只是10.如果你想要小数位数是重要的,你需要使用0

new DecimalFormat("#.0");

Sample output for this would be: 此示例输出将是:

0.11 - .1
10.00 - 10.0
10.4545 - 10.5
.00 - .0
455 - 455.0

If you want a 0 before decimal too, then you can user #0.0 如果你想在小数点前加0,那么你可以用#0.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM