java如何保留小数点后两位

方法有好多种,在这里列出来4种:
1、用format方法,语法“String.format(“%.2f”,数值)”;

String的format方法(推荐)

double f = 111231.5585;

System.out.println(String.format("%.2f", f));

2、用DecimalFormat的format方法;
DecimalFormat的format方法

double f = 111231.5585;

DecimalFormat df = new DecimalFormat("#.00");            

System.out.println(df.format(f));

3、用setScale方法进行四舍五入;

BigDecimal的setScale方法

double f = 111231.5585;

BigDecimal bg = new BigDecimal(f);            

double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();            

System.out.println(f1);

4、用setMaximumFractionDigits方法。

NumberFormat的setMaximumFractionDigits方法

double f = 111231.5585;

NumberFormat nf = NumberFormat.getNumberInstance();            

nf.setMaximumFractionDigits(2);            

System.out.println(nf.format(f));

 

请登录后发表评论

    没有回复内容