下午改以前的项目的时候遇到了一个小的问题,大概就是需要把 "100G/500G" 这个字符串转换成 "20%",然后我就想到了如下的解决办法
1.先用string的方法把100和500单独取出来
//设置初始值
String str = "100G/500G";
//拿到前面的数
str.subSequence(0, str.indexOf("G"));
CharSequence strFirst = str.subSequence(0, str.indexOf("G"));
String strFirst1 = strFirst.toString();
//拿到后面的数
str.subSequence(str.indexOf("G")+2, str.length()-1);
CharSequence strLast = str.subSequence(str.indexOf("G")+2, str.length()-1);
String strLast1 = strLast.toString();
拿到了【100】和【500】
2.对这两个字符串转成double类型后进行运算
double strFirstDou = Double.parseDouble(strFirst1);
double strLastDou = Double.parseDouble(strLast1);
//计算容量
double capacity = strFirstDou / strLastDou;
拿到了【0.2】
3.将浮点型数字转换成百分比并保存两位小数
//获取格式化对象 getPercentInstance是百分比方法
NumberFormat nt = NumberFormat.getPercentInstance();
//设置百分数精确度2即保留两位小数
nt.setMinimumFractionDigits(2);
//最后格式化并输出
String capacityDou = nt.format(capacity);
得到了【20%】
然后把这些代码捏合到一个方法当中,用的次数多的话直接调用就行了
public static String capacity(String str){
//拿到前面的数
str.subSequence(0, str.indexOf("G"));
CharSequence strFirst = str.subSequence(0, str.indexOf("G"));
String strFirst1 = strFirst.toString();
double strFirstDou = Double.parseDouble(strFirst1);
//拿到后面的数
str.subSequence(str.indexOf("G")+2, str.length()-1);
CharSequence strLast = str.subSequence(str.indexOf("G")+2, str.length()-1);
String strLast1 = strLast.toString();
double strLastDou = Double.parseDouble(strLast1);
//计算容量
double capacity = strFirstDou / strLastDou;
//获取格式化对象
NumberFormat nt = NumberFormat.getPercentInstance();
//设置百分数精确度2即保留两位小数
nt.setMinimumFractionDigits(2);
//最后格式化并输出
String capacityDou = nt.format(capacity);
return capacityDou;
}