Java float类型怎么把小数位数限制为2位

转载自 https://blog.csdn.net/u012988145/article/details/39454797

1.double d = 22.363434;
 BigDecimal a=new BigDecimal(d);
 //直接省略后面的
 a.setScale(2,1);
 //四舍五入
 a.setScale(2,2);


2.double value = 22.363434;
DecimalFormat df = new DecimalFormat("########.00");
//四舍五入
value = Double.parseDouble(df.format(value));


java中float,double的小数点后面限制位数的方法

我以一个小数点后面保留两位为例:(都是四舍五入)

1.

 import java.text.DecimalFormat;

double x=23.5455;

NumberFormat format1=NumberFormat.getNumberInstance() ;
format1.setMaximumFractionDigits(2);

String s = format1.format(x);

2.

 import java.text.DecimalFormat;

DecimalFormat format2 = new DecimalFormat( "0.00 "); 

double x=23.5455;

x = Double.parseDouble(format2.format(x));

 

最近想到第三种方法:

3.下面我以小数点后面两位为例,先扩大100倍进行四舍五入,然后除以100转为double就可以,我喜欢这方法,就可以不用去记住其他方法了。***3位小数为1000,4位则10000

 double x=23.5455;

 x = (double)Math.round((double)(x*100))/100;


猜你喜欢

转载自blog.csdn.net/u012240455/article/details/80774628