今天要将输出的许多double型数存入文件,发现文件大小较大,于是想到把它们都保留4位小数。发现实现这样还是不少方法的。
 
1.比较简单。采用BigDecimal,详见jdk doc
       import java.math.BigDecimal;
 
       double dout=28.965432;
       BigDecimal bd= new BigDecimal(dout); 
       bd=bd.setScale(4, BigDecimal.ROUND_HALF_UP); 
       System.out.println(bd.doubleValue());
 
2.也是一种不少人提出的思路。
       Baoliu(double dout,int n){
             double p= Math.pow(10, n); 
             return Math.round( x * p ) / p;
       } 
附:
Math.round( )
static longround(double a)
          Returns the closest long to the argument.
static intround(float a)
          Returns the closest int to the argument.
 
当然关于这个实现的方法好像还挺多的。慢慢学吧
 
3.更多关于Java的数据格式化