Java float保留两位小数或多位小数

古城微笑少年丶 2023-07-03 10:34 96阅读 0赞

方法1:用Math.round计算,这里返回的数字格式的.

  1. float price=89.89;
  2. int itemNum=3;
  3. float totalPrice=price*itemNum;
  4. float num=(float)(Math.round(totalPrice*100)/100);//如果要求精确4位就*10000然后/10000

方法2:用DecimalFormat 返回的是String格式的.该类对十进制进行全面的封装.像%号,千分位,小数精度.科学计算.

  1. float price=1.2;
  2. DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
  3. String p=decimalFomat.format(price);//format 返回的是字符串

个人觉得在前台显示金额方面的还是用第二种方式.理由很简单是字符串格式的.

发表评论

表情:
评论列表 (有 0 条评论,96人围观)

还没有评论,来说两句吧...

相关阅读