项目要对一个double值保留小数点后3位,网上找到好几种方法,选一个用在项目中,实测发现有误差,再换一种,还是会有误差。最后经过多种情况测试,发现最后2种是精确的。
- package com.example.testndk;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.text.DecimalFormat;
- import java.text.NumberFormat;
- /**
- * Created by D.bj on 2017/1/5.
- */
- public class DoubleTest {
- /**
- * 保留3位小数,四舍五入的一个老方法
- * @param d
- * @return
- */
- public 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
- */
- public 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
- */
- public 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
- */
- public 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
- */
- public static String formatDouble5(double d) {
- String str = String.format("%.3f", d);
- // double dscore = Double.parseDouble(str);
- return 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));
- }
- }