将双倍数字四舍五入到 3 个有效数字

2022-09-01 13:43:37

有谁知道我如何将双倍值四舍五入为3个有效数字,就像这个网站上的例子一样

http://www.purplemath.com/modules/rounding2.htm


答案 1
double d = ...;
BigDecimal bd = new BigDecimal(d);
bd = bd.round(new MathContext(3));
double rounded = bd.doubleValue();

答案 2

如果你想手工做:

import java.lang.Math;

public class SigDig {

  public static void main(String[] args) {
    System.out.println("   -123.456   rounded up   to 2 sig figures is " + sigDigRounder(-123.456, 2,  1));
    System.out.println("     -0.03394 rounded down to 3 sig figures is " + sigDigRounder(-0.03394, 3, -1));
    System.out.println("    474       rounded up   to 2 sig figures is " + sigDigRounder(474, 2,  1));
    System.out.println("3004001       rounded down to 4 sig figures is " + sigDigRounder(3004001, 4, -1));
  }

  public static double sigDigRounder(double value, int nSigDig, int dir) {

    double intermediate = value/Math.pow(10,Math.floor(Math.log10(Math.abs(value)))-(nSigDig-1));

    if(dir > 0)      intermediate = Math.ceil(intermediate);
    else if (dir< 0) intermediate = Math.floor(intermediate);
    else             intermediate = Math.round(intermediate);

    double result = intermediate * Math.pow(10,Math.floor(Math.log10(Math.abs(value)))-(nSigDig-1));

    return(result);

  }
}

上述方法将双倍数舍入为所需数量的有效数字,处理负数,并且可以明确地告诉向上或向下舍入