BigBug
BigBug

Reputation: 6290

convert BigDecimal to Scientific Notation Java

How do i print this in scientific notation:

BigDecimal r= (a.subtract(exact, MathContext.DECIMAL128)).divide(exact, MathContext.DECIMAL128).stripTrailingZeros();
DecimalFormat format = new DecimalFormat("0.###E0");
System.out.println(new BigDecimal(format.format(r));

where:

a = 1.111111111111111160454356650006957352161407470703125
exact = 0.11

returns:

r = 0.900010000000000004

any ideas? I've also tried calling EngineeringString() on the BigDecimal but this also didn't seem to work for me

Upvotes: 0

Views: 1172

Answers (1)

ppeterka
ppeterka

Reputation: 20726

You overdid the thing. What you only need is:

System.out.println(format.format(r));

The DecimalFormat object does indeed create a string, creating a BigDecimal instance again would just parse the number from string again - and the toString() method is called on the BigDecimal instance, produing the output you described...

Some clarification

BigDecimal, and other numeric formats (and dates too!) are stored in binary formats in the memory, abstracted from how us, humans think of them. BigDecimal for example stores the decimal digits, and where the decimal point is. Floating point numbers are even more sophisticated. Date stores the seconds from The Epoch. You need to format them to be readable. Formatting means to create a String (or semantically similar) object, that represents the value of the given object in the desired format. This doesn't involve changing the original object in any way.

The default formatting, toString() provides one generic format. To get your output the way you'd like does not mean to change the value to be formatted right with toString(), but to transform the unchanged value into the right String. Nice example is Double.toString() (using sun.mic.FloatingDecimal): it does exponential notation when the number is large or small enough, but in between, it prints in plain decimal format...

Upvotes: 4

Related Questions