double保留两位小数(四舍五入)
程序员文章站
2022-04-08 13:53:37
...
//val为处理double 数字,precsion为保留小数位数。
public static Double roundDouble(double val, int precision) {
Double ret = null;
try {
double factor = Math.pow(10, precision);
ret = Math.floor(val * factor + 0.5) / factor;
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
// 格式化数据
//将小数转化为百分数,保留2位小数,四舍五入,例:35.21%
public static String formatRates(double val ) {
Double ret = null;
val = val*100 ;
int precision = 2 ;
try {
double factor = Math.pow(10, precision);
ret = new Double(Math.floor(val * factor + 0.5) / factor);
} catch (Exception e) {
e.printStackTrace();
}
String tmp = String.valueOf(ret);
if (tmp.substring(tmp.indexOf('.')+1).length()<2){
tmp = tmp + "0" ;
}
return tmp + "%";
}
写道
public static String getRoundValue(double value,int digit) {
digit = (digit < 0 ? 0 : digit );
String s = String.valueOf(new BigDecimal(value).setScale(digit, BigDecimal.ROUND_HALF_UP)
.doubleValue());
return (digit == 0 ? (s.substring(0,s.indexOf('.'))) : s);
}
digit = (digit < 0 ? 0 : digit );
String s = String.valueOf(new BigDecimal(value).setScale(digit, BigDecimal.ROUND_HALF_UP)
.doubleValue());
return (digit == 0 ? (s.substring(0,s.indexOf('.'))) : s);
}