初学Java:保留小数位数方法

来源:互联网 发布:织梦cms重新安装 编辑:程序博客网 时间:2024/06/06 18:51

方法1:

import java.math.BigDecimal;

public class Test1 {

public static void main(String[] args) {
double f=121.3463785;
BigDecimal b=new BigDecimal(f);
double f1=b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f+" "+f1);
}

}

方法二:

import java.text.DecimalFormat;


public class Test2 {


public static void main(String[] args) {
double f=121.3463785;
DecimalFormat f1=new DecimalFormat("#.00");
System.out.println(f1.format(f));
}


}

方法3:使用String类中的format方法格式化数字

public class Test3 {


public static void main(String[] args) {
double f=235.356546;
String result=String.format("%.2f",f);
System.out.println(result);
}


}


原创粉丝点击