/**
* 提供精确的小数位四舍五入处理,显示指定格式数字。
*
* @param d
* 需要四舍五入的数字
* @param scale
* 小数点后保留几位
* @return (string型) 四舍五入后的结果
*/
public static String roundString(double d, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(d));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 提供精确的小数位四舍五入处理,显示指定格式数字。
*
* @param d
* 需要四舍五入的数字
* @param scale
* 小数点后保留几位
* @return (double型) 四舍五入后的结果
*/
public static double roundDouble(double d, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(d));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
Java中指定小数位数进行四舍五入处理方法 - Java
最新推荐文章于 2024-07-08 10:32:28 发布