我被分配输出 double :
myD=1.0/3.0; //using println as 0.33333334 = 1/3.
我尝试使用一些格式,但没有成功。
//0.33333334 = 1/3; //only using println
double myD = 1.0/3.0
System.out.println("%0.8f", myD);
0.33333334
最佳答案
使用DecimalFormat
并将舍入模式设置为始终舍入到CEILING
。
double myD = 1.0/3.0;
DecimalFormat df = new DecimalFormat("#.########");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println(df.format(myD));
输出:
0.33333334
如果您不需要四舍五入,则可以只使用 String.format
来获取 0.33333
:
System.out.println(String.format("%.8f", myD));
输出:
0.33333333
当然,也可以是 System.out.format("%.8f", myD);
,但要求要求使用 System.out.println
。
关于java - 我试图使用 println 将 double 中的小数位数减少到 8 并将最后一位数字向上舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57891388/