一、场景引入
如果前端页面存在列表展示用户数据,但是用户数据存在非常多的小数位,从页面来看,数据太多就会不太美观,因此,出于场景美化考虑,在不影响业务功能的情况下,可以只展示整数内容;
二、具体实现
1、使用Decimal.format()来进行转换
@Testpublic void test1(){DecimalFormat decimalFormat = new DecimalFormat("0");String price = "10086.112";Double priceDou = Double.parseDouble(price);//注意,方法的返回值是一个String类型数据String priceFormat = decimalFormat.format(priceDou);System.out.println(priceFormat.concat("元"));}
本地演示操作结果:
注意:此种方法只会直接拿到整数部分,并且返回值为String,小数部分会直接丢失;
2、借助Double的intValue()方法
@Testpublic void test2(){String price = "10086.112";String percent = "10086.303";String cash = "10086.600";Double priceDou = Double.parseDouble(price);Double percentDou = Double.parseDouble(percent);Double cashDou = Double.parseDouble(cash);int priceInt = priceDou.intValue();int percentInt = percentDou.intValue();int cashInt = cashDou.intValue();System.out.println(priceInt);System.out.println(percentInt);System.out.println(cashInt);}
注意:在此种方法当中,也是会将小数部分直接丢弃,不会涉及到数据的四舍五入;
3、借助Math.round()方法--可以四舍五入
@Testpublic void test3(){String price = "10086.112";String percent = "10086.303";String cash = "10086.600";//先将String转换成numberDouble priceDou = Double.parseDouble(price);Double percentDou = Double.parseDouble(percent);Double cashDou = Double.parseDouble(cash);//对number进行四舍五入转换,此时已经是个长整型的数据long priceL = Math.round(priceDou);long percentL = Math.round(percentDou);long cashL = Math.round(cashDou);//取整int priceInt = Integer.parseInt(String.valueOf(priceL));int percentInt = Integer.parseInt(String.valueOf(percentL));int cashInt = Integer.parseInt(String.valueOf(cashL));System.out.println("periceInt: "+priceInt+"\npercentInt: "+percentInt+"\ncashInt:"+cashInt);}
控制台显示结果:
4、借助bigDecimal对象的setScale(需要保留的小数位,转换的规则)方法,四舍五入取整
@Testpublic void test4(){String price = "10086.112";String percent = "10086.303";String cash = "10086.600";//四舍五入BigDecimal priceBig = new BigDecimal(price).setScale(0, BigDecimal.ROUND_HALF_UP);BigDecimal percentBig = new BigDecimal(percent).setScale(0,BigDecimal.ROUND_HALF_UP);BigDecimal cashBig = new BigDecimal(cash).setScale(0,BigDecimal.ROUND_HALF_UP);//先将bigDecimal的变量转换成String,再转换成int取整int priceInt = Integer.parseInt(String.valueOf(priceBig));int percentInt = Integer.parseInt(String.valueOf(percentBig));int cashInt = Integer.parseInt(String.valueOf(cashBig));System.out.println("periceInt: "+priceInt+"\npercentInt: "+percentInt+"\ncashInt:"+cashInt);}
控制台结果: