Java float浮点型保留2位小数

方法1、用Math.round计算,这里返回的数字格式的:
float price=99.69537f;
int itemNum=3;
float totalPrice=price*itemNum;
float num=(float)(Math.round(totalPrice*100)/100);//这里的100就是2位小数点,如果要求精确4位就*10000然后/10000



方法2、用DecimalFormat 返回的是String格式的.该类对十进制进行全面的封装.像%号,千分位,小数精度.科学计算:
float price=1.20123f;
DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
String strPrice = decimalFormat.format(price);//返回字符串

 

DecimalFormat 的千分位格式化如下:

String   a   =  new  DecimalFormat("###,###,###.##").format(100.12345  );


方法3、通过BigDecimal转换:
  float   price   =  34.231313f;  
  BigDecimal   b  =   new  BigDecimal(price);  
  float   m_price   =  b.setScale(2,  BigDecimal.ROUND_HALF_UP).floatValue(); 

BigDecmal保留小数位可以参考下面:

猜你喜欢

转载自blog.csdn.net/xuwei_net/article/details/81975455