I am trying to convert String value to BigDecimal value. when i use 0.000001234 I am getting same value in BigDecimal. But, when I use 0.000000123 or 0.000000012 I am getting 1.23E-7 or 1.2E-8.
I need like below, if input is String = 0.000000123
Then output should be, BigDecimal = 0.000000123
Please help me
import java.math.BigDecimal;
public class DecimalEx {
public static void main(String args[]){
String s = "0.000000023";
BigDecimal big = new BigDecimal(s);
System.out.println(big);
}
}
You're converting the String
to a BigDecimal
with no problems. The BigDecimal
value has no notion of whether the value has exponential notation or not... it's just a scaled value.
The problem you're seeing is when you implicitly call BigDecimal.toString()
, which is documented to use exponential notation sometimes:
If the scale is greater than or equal to zero and the adjusted exponent is greater than or equal to -6, the number will be converted to a character form without using exponential notation.
Instead, you want to use BigDecimal.toPlainString()
:
Returns a string representation of this BigDecimal without an exponent field.
Just change your last line of code to:
System.out.println(big.toPlainString());
See more on this question at Stackoverflow