Java小数中的四舍五入
1.怎么设置显示小数位数
public static void main(String[] args) { DecimalFormat decimalFormat = new DecimalFormat("0.00"); Random random = new Random(); for (int i = 0; i < 20; i++) { double v = random.nextDouble(); System.out.println("double = "+v+", format = " + decimalFormat.format(v)); }
}
默认四舍五入,源码里面有七八种舍的方法,不知道具体的区别
2.进一法设置(后面全部不要,然后前面进一)
public static void main(String[] args) { DecimalFormat decimalFormat = new DecimalFormat("0.00"); decimalFormat.setRoundingMode(RoundingMode.UP); // 进一法 Random random = new Random(); for (int i = 0; i < 20; i++) { double v = random.nextDouble(); System.out.println("double = "+v+", format = " + decimalFormat.format(v)); } }
3.当然还有不进行四舍五入的例子
public static void main(String[] args) { DecimalFormat decimalFormat = new DecimalFormat("0.00"); decimalFormat.setRoundingMode(RoundingMode.DOWN); // 不进行四舍五入 Random random = new Random(); for (int i = 0; i < 20; i++) { double v = random.nextDouble(); System.out.println("double = "+v+", format = " + decimalFormat.format(v)); } }