[英]Rounding off a double to 3 digit decimal place but zero at 3rd decimal place disappears in java
I want to round of my double to 3 decimal places in java. 我想在Java中将我的双精度舍入到小数点后第3位。
I don't want to trim off the zero. 我不想削减零。 So if my double is 2.34, I still want it as 2.340.
因此,如果我的倍数是2.34,我仍然希望它是2.340。
DecimalFormat myFormatter = new DecimalFormat("0.000");
String output = myFormatter.format(2.34d);
String res = String.format("%.3f", 2.34);
或者如果您想打印
System.out.printf( "%.3f",2.34);
use setMinimumFractionDigits and setRoundingMode 使用setMinimumFractionDigits和setRoundingMode
final DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(3);
df.setRoundingMode(RoundingMode.HALF_UP);
df.format(2.34);
使用以下十进制格式: 0.000
Following on from Tony Ennis's comment, you can't round a floating-point variable to a specific number of decimal places, or digits, without converting it into base-10. 根据Tony Ennis的评论,您不能将浮点变量四舍五入到特定的小数位数或位数, 而无需将其转换为10进制。 That's what the answers above are doing, and they are also converting it into displayable text.
这就是上面的答案,他们还将其转换为可显示的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.