永发信息网

java中如何实现将float精确到小数点后两位

答案:3  悬赏:30  手机版
解决时间 2021-02-06 03:19
  • 提问者网友:活着好累
  • 2021-02-05 13:52
比如 float f = 0.123456怎么弄成0.12(四舍五入)
最佳答案
  • 五星知识达人网友:神也偏爱
  • 2021-02-05 14:56



方法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 返回的是字符串
全部回答
  • 1楼网友:有你哪都是故乡
  • 2021-02-05 17:17
你好,float,double默认值为0.0; 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;
  • 2楼网友:街头电车
  • 2021-02-05 16:14
Math.round(f*100.001)/100.0
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯