Java 除法保留N位小数,计算百分比

java 两个整数相除保留两位小数:

https://blog.csdn.net/qq_26676207/article/details/53375263

1、方法1

int a=1099;
int b=93;

double f1 = new BigDecimal((float)a/b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

System.out.println("ddd==="+f1);

2、方法2


int a=1099;
int b=93; 

DecimalFormat df = new DecimalFormat("0.00");//格式化小数  
String num = df.format((float)a/b);//返回的是String类型  

System.out.println("ddd==="+num);
 

====================

计算百分比【计算除法时,用的是 上面的方法1】

//BigDecimal 格式化工具    保留两位小数
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(2);

//除法结果保留4位小数,
double per = new BigDecimal((float)a/b).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue();

//格式化为百分比字符串(自带百分号)
String Ratio = percent.format(per);

猜你喜欢

转载自blog.csdn.net/NRlovestudy/article/details/89419574
今日推荐