1

I am looking to print small digits (doubles) for the purpose of printing the errors in using the Newton & Secant methods.

One of my errors is 5.433306166802499E-5

I'd like to print 5.4333E-5

I thought of using BigDecimal but I am not familiar with this class.

sisanared
  • 4,175
  • 2
  • 27
  • 42

4 Answers4

6

I am looking to print small digits (doubles)

System.out.printf("%.4e",  5.433306166802499E-5);

Result: 5.4333e-05

Note: it doesn't reduce the precision of your original value, it just prints it with a lower precision.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23
2

double d = 5.433306166802499E-5; BigDecimal dc = new BigDecimal(d); dc = dc .round(new MathContext(3)); // desired significant digits double rounded = dc .doubleValue();

Ghost Developer
  • 1,283
  • 1
  • 10
  • 18
1

You can indeed use BigDecimal, it would then look as follows:

BigDecimal d = BigDecimal.valueOf(val).setScale(scale, RoundingMode.HALF_UP);
double scaled = d.doubleValue();

Or you could use:

Math.round(val*Math.pow(10, scale))/Math.pow(10, scale);
Lucurious
  • 174
  • 6
  • First example as too many commas, and if `val = 5.433306166802499E-5` as given in question, result is `1.0E-4`, which is far from the desired output of `5.4333E-5`. – Andreas Oct 20 '16 at 06:37
-1

To answer the general question of reducing a double's significant digits, and not just the case of printing with System.out.printf:

If you're using Java: Double.parseDouble(String.format("%1.4e", 5.433306166802499E-5))

In Scala, you can use the f string interpolator, or the format method:

val a: Double = 5.433306166802499E-5
val reduced1: Double = f"$a%1.4e".toDouble
val reduced2: Double = "%1.4e".format(a).toDouble

Both are equal: 5.4333e-05