码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-08 10:56:42      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

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

标签:

原文地址:http://www.cnblogs.com/emanlee/p/4629477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!