项目要对一个double值保留小数点后3位,网上找到好几种方法,选一个用在项目中,实测发现有误差,再换一种,还是会有误差。最后经过多种情况测试,发现最后2种是精确的。
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* @author zhangjiaxiang
* @date 2019/8/9 10:48
*/
public class DoubleTest {
/**
* 保留3位小数,四舍五入的一个老方法
*
* @param d 传参
* @return double
*/
private static double formatDouble1(double d) {
return (double) Math.round(d * 1000) / 1000;
}
/**
* The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
*
* @param d 传参
* @return double
*/
private static double formatDouble2(double d) {
// 旧方法,已经不再推荐使用
// BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);
// 新方法,如果不需要四舍五入,可以使用RoundingMode.DOWN
BigDecimal bg = new BigDecimal(d).setScale(3, RoundingMode.UP);
return bg.doubleValue();
}
/**
* NumberFormat is the abstract base class for all number formats.
* This class provides the interface for formatting and parsing numbers.
*
* @param d 传参
* @return double
*/
private static String formatDouble3(double d) {
NumberFormat nf = NumberFormat.getNumberInstance();
// 保留3位小数
nf.setMaximumFractionDigits(3);
// 如果不需要四舍五入,可以使用RoundingMode.DOWN
nf.setRoundingMode(RoundingMode.UP);
return nf.format(d);
}
/**
* DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers.
*
* @param d 传参
* @return double
*/
private static String formatDouble4(double d) {
DecimalFormat df = new DecimalFormat("#0.000");
return df.format(d);
}
/**
* 如果只是用于程序中的格式化数值然后输出,那么这个方法还是挺方便的。
* 应该是这样使用:System.out.println(String.format("%.3f", d));
*
* @param d 传参
* @return double
*/
private static double formatDouble5(double d) {
String str = String.format("%.3f", d);
return Double.parseDouble(str);
}
public static void main(String[] args) {
double d = 0.001254;
System.out.println(formatDouble1(d));
System.out.println(formatDouble2(d));
System.out.println(formatDouble3(d));
System.out.println(formatDouble4(d));
System.out.println(formatDouble5(d));
}
}
运行结果:
补充:
四舍五入取整 ======》大于0.5进一
四舍五入取整 ======》0.5舍去,0.51进一
四舍五入凑整 ======》小数点舍去,进一(前提小数点后大于0.00)
//四舍五入把double转化int整型,0.5进一,小于0.5不进一
public static int getInt(double number) {
BigDecimal bd = new BigDecimal(number).setScale(0, BigDecimal.ROUND_HALF_UP);
return Integer.parseInt(bd.toString());
}
//四舍五入把double转化为int类型整数,0.5也舍去,0.51进一
public static int DoubleFormatInt(Double dou) {
DecimalFormat df = new DecimalFormat("######0"); //四色五入转换成整数
return Integer.parseInt(df.format(dou));
}
//去掉小数凑整:不管小数是多少,都进一
public static int ceilInt(double number) {
return (int) Math.ceil(number);
}