Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java BigDecimal return 1E+1?

Why does this code sometimes return 1E+1 whilst for other inputs (e.g. 17) the output is not printed in scientific notation?

BigDecimal bigDecimal = BigDecimal.valueOf(doubleValue).multiply(BigDecimal.valueOf(100d)).stripTrailingZeros(); System.out.println("value: " + bigDecimal); 
like image 392
parkr Avatar asked May 29 '09 09:05

parkr


People also ask

What is the default value of BigDecimal in Java?

If you are using type BigDecimal, then its default value is null (it is object, not primitive type), so you get [1] automatically.

How many digits can BigDecimal hold in Java?

It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

What is the limit of BigDecimal in Java?

The largest value BigDecimal can represent requires 8 GB of memory.

What is BigDecimal one in Java?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.


2 Answers

use bigDecimal.toPlainString():

 BigDecimal bigDecimal = BigDecimal.valueOf(100000.0)                      .multiply(BigDecimal.valueOf(100d))                      .stripTrailingZeros();  System.out.println("plain      : " + bigDecimal.toPlainString());  System.out.println("scientific : " + bigDecimal.toEngineeringString()); 

outputs:

 plain      : 10000000 scientific : 10E+6 
like image 152
dfa Avatar answered Oct 02 '22 09:10

dfa


It's the implicit .toString() conversion that is happening when you pass the result into System.out.println().

like image 38
Jordan S. Jones Avatar answered Oct 02 '22 11:10

Jordan S. Jones