我正在编写一个简单的java程序.我需要从输入中获取一个字符串并将其分为两部分:1-double 2-string.然后我需要对double进行简单的计算,并以特定的精度将结果发送到输出(4).它工作正常,但输入为0时出现问题,然后它无法正常工作.
例如,对于这些输入,输出将是:
1公斤
产量:2.2046
3.1千克
产量:6.8343
但是当输入为0时,输出应为0.0000,但显示为0.0.我应该怎么做才能强制显示0.0000?
我读过关于双精度的类似帖子,他们建议类似于BigDecimal类,但在这种情况下我不能使用它们,我这样做的代码是:
line=input.nextLine();
array=line.split(" ");
value=Double.parseDouble(array[0]);
type=array[1];
value =value*2.2046;
String s = String.format("%.4f", value);
value = Double.parseDouble(s);
System.out.print(value+" kg\n");
Run Code Online (Sandbox Code Playgroud)
将此 DecimalFormat 实例添加到方法的顶部:
DecimalFormat four = new DecimalFormat("#0.0000"); // will round and display the number to four decimal places. No more, no less.
// the four zeros after the decimal point above specify how many decimal places to be accurate to.
// the zero to the left of the decimal place above makes it so that numbers that start with "0." will display "0.____" vs just ".____" If you don't want the "0.", replace that 0 to the left of the decimal point with "#"
Run Code Online (Sandbox Code Playgroud)
然后,调用实例“four”并在显示时传递双精度值:
double value = 0;
System.out.print(four.format(value) + " kg/n"); // displays 0.0000
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62680 次 |
| 最近记录: |