/**
* 分数转小数
*
* @param str
* @return
*/
public static BigDecimal fractionToDecimal(String str) {
Integer numerator = Integer.valueOf(str.substring(0,str.lastIndexOf("/")));
Integer denominator = Integer.valueOf(str.substring(str.lastIndexOf("/") + 1));
long x = numerator,y = denominator;
if(x % y == 0) return new BigDecimal("" + x / y);
String res = "";
// 如果同号则为0,不同则为1,加上一个负号
if((x < 0) ^ (y < 0)) res += '-';
x = Math.abs(x);
y = Math.abs(y);
// 记录商
res += x / y + ".";
// x此时表示余数
x %= y;
// 用哈希表记录所有出现过的余数
Map<Long,Integer> hashmap = new HashMap<>();
// x == 0表示除尽了
while(x != 0){
// 记录当前余数对应的商是多少位
hashmap.put(x,res.length());
x *= 10; // 余数每次要乘10再进行除法操作 --- 模拟除法
res += x / y;
x %= y;
// 如果出现了重复的余数
if(hashmap.containsKey(x)){
res = res.substring(0,hashmap.get(x)) + "" + res.substring(hashmap.get(x));
break;
}
}
return new BigDecimal(res);
}
/**
* 百分数转为小数
* @param str
* @return
*/
public static BigDecimal PercentageToDecimal(String str) {
BigDecimal decimal;
NumberFormat nf=NumberFormat.getPercentInstance();
try {
decimal = new BigDecimal(nf.parse(str).toString());
} catch (ParseException e) {
throw new DataException("百分数转换异常");
}
return decimal;
}
/**
* 是否为百分数
* @param str
* @return
*/
public static Boolean isPercentage(String str){
if (StringHelperDomain.isEmpty(str)){
return false;
}
return str.endsWith("%");
}
Java 分数转小数、百分数转小数
最新推荐文章于 2024-04-19 22:14:49 发布