Reputation: 3
double d =0.0000001;
BigDecimal d1 = BigDecimal.valueOf(d);
System.out.println(d1.toPlainString());
prints output => 0.00000010
i am expecting 0.0000001
Upvotes: 0
Views: 4066
Reputation: 28806
First, to get a precise BigDecimal
value, avoid using a float
or double
to initialize it. The conversion from text to floating point type is by definition not guaranteed to be precise. The conversion from such a type to BigDecimal
is precise, but may not exactly yield the result you expected.
If you can avoid using a double
or float
for initialization, then do something like this instead:
BigDecimal d = new BigDecimal("0.0000001");
This will already give you the desired output, because the conversion from (decimal) text to BigDecimal
is precise.
But if you really must convert from a double
, then try:
double d = 0.0000001;
BigDecimal d1 = BigDecimal.valueOf(d);
System.out.println(d1.stripTrailingZeros().toPlainString());
This will strip (remove) any trailing zeroes.
Upvotes: 1
Reputation: 108
You can use a DecimalFormat
to format your BigDecimal
.
double d = 0.0000001;
BigDecimal d1 = BigDecimal.valueOf(d);
DecimalFormat df = new DecimalFormat("#0.0000000");
System.out.println(df.format(d1));
Upvotes: 0