# 四舍五入到三位有效数字

#### Round a double to 3 significant figures

7 个回复
``````double d = ...;
BigDecimal bd = new BigDecimal(d);
bd = bd.round(new MathContext(3));
double rounded = bd.doubleValue();
``````
``````    public String toSignificantFiguresString(BigDecimal bd, int significantFigures ){
String test = String.format("%."+significantFigures+"G", bd);
if (test.contains("E+")){
test = String.format(Locale.US, "%.0f", Double.valueOf(String.format("%."+significantFigures+"G", bd)));
}
return test;
}
``````

``````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);

}
}
``````

Sean Owen（ https://stackoverflow.com/a/7548871/274677 ）给出的答案没有错。 但是，根据您的用例，您可能需要使用String表示形式。 在这种情况下，IMO最好仍在BigDecimal空间中使用以下方法进行转换：

``````bd.toPlainString();
``````

...如果这是您的用例，那么您可能会感到沮丧，根据Owen的答案改编的代码将产生以下内容：

``````d = 0.99, significantDigits = 3 ==> 0.99
``````

...而不是严格更精确的`0.990`

``````public static String setSignificanDigits(double value, int significantDigits) {
if (significantDigits < 0) throw new IllegalArgumentException();

// this is more precise than simply doing "new BigDecimal(value);"
BigDecimal bd = new BigDecimal(value, MathContext.DECIMAL64);
bd = bd.round(new MathContext(significantDigits, RoundingMode.HALF_UP));
final int precision = bd.precision();
if (precision < significantDigits)
bd = bd.setScale(bd.scale() + (significantDigits-precision));
return bd.toPlainString();
}
``````

``````public class RoundingCounterExample
{
static float roundOff(float x, int position)
{
float a = x;
double temp = Math.pow(10.0, position);
a *= temp;
a = Math.round(a);
return (a / (float)temp);
}

public static void main(String[] args)
{
float a = roundOff(0.0009434f,3);
System.out.println("a="+a+" (a % .0001)="+(a % 0.001));
int count = 0, errors = 0;
for (double x = 0.0; x < 1; x += 0.0001)
{
count++;
double d = x;
int scale = 2;
double factor = Math.pow(10, scale);
d = Math.round(d * factor) / factor;
if ((d % 0.01) != 0.0)
{
System.out.println(d + " " + (d % 0.01));
errors++;
}
}
System.out.println(count + " trials " + errors + " errors");
}
}
``````

``````// yeah, I know this is just Math.PI.
double myDouble = 3.141592653589793;
DecimalFormat myFormat = new DecimalFormat("0.000");
String myDoubleString = myFormat.format(myDouble);
System.out.println("My number is: " + myDoubleString);

// or you can use printf which works like String.format:
System.out.printf("My number is: %.3f%n", myDouble);
``````
1 指定Django DecimalField的有效位数

Django 文档很清楚，DecimalFields是基于Python 十进制模块的固定精度十进制数字。 如果我已有12位有效数字的数据，该如何对其建模？ 例如，这是感兴趣的数据的示例： 一些条目只有6个小数，而其他条目则有9或10个小数。由于这只是数据集中的一个样本，因此可 ...

2 计算有效位数

2017-08-22 15:59:02 1 309   ruby
3 读取.png的有效位数？

2016-11-04 18:52:33 1 68   png
5 浮点类型的有效位数

C中类型float的描述提到有效位数是6 。 然而， 然后使用printf（）打印它不打印12345.6 ，它打印12345.599609 。 那么对于浮点类型，“6位有效数字”（或“ double情况下为15”）意味着什么呢？ ...

6 四舍五入到Postgres中的有效位数

2016-03-02 16:14:19 0 518   to-char
7 在Python中如何找到最低有效位数

8 找到C＃decimal的最低有效位数

9 R：选择列表的有效位数

2017-07-17 03:29:34 0 60   r/ list