double及float转换为整数及控制小数点位数显示

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wfs31415926/article/details/85112671

1.直接转换为整数:

int result=Math.round(price);//四舍五入
int result=Math.ceil(price);//天花板 大于或等于的最小整数
int result=Math.floor(price);//地板  小于或等于的最大整数

2.控制小数点位数及末尾零是否显示(四舍五入)
末尾零显示

 DecimalFormat decimalFormat = new DecimalFormat(".0");//构造方法的字符格式   一个0表示显示一位小数 这里如果小数不足1位,会以0补足. 
String p = decimalFormat.format(price);//format 返回的是字符串

末尾零不显示

   DecimalFormat decimalFormat = new DecimalFormat("###.##");//构造方法的字符格式   两个#表示显示2位小数 这里如果小数 末尾为0,不显示. 
     String p = decimalFormat.format(price);//format 返回的是字符串

猜你喜欢

转载自blog.csdn.net/wfs31415926/article/details/85112671