java保留double类型固定小数位数的方法

方法一:

用String类的format方法

例如:

double    x = 1.23456789
System.out.println(String.format("%.6f", x));   //表示四舍五入保留六位小数。
System.out.println(String.format("%.3f", x));   //表示四舍五入保留3位小数 输出为1.235


方法二:

Math中的round方法

System.out.println((double)Math.round(x*1000)/1000.0); //表示四舍五入保留x小数点后三位小数结果为1.235


方法三:

DecimalFormat 类

DecimalFormat  formatDouble = new DecimalFormat("#.######"); //表示格式化为保留小数后六位
System.out.println(formatDouble.format(x));//输出结果为1.234568


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章