I want to pass a decimal number that is in a variable of type String to one of type Double, but before applying a specific format with DecimalFormat (import java.Text.DecimalFormat) so that it always has 3 decimal places. When performing the conversion I always lose decimals, more exactly the decimals that are 0 to the right.
Do you know how to perform this conversion without losing that precision?
I have found that using the BigDecimal type does the trick, but I would like to do this conversion without using it.
Cheers,
For example:
Double d = 0.85; // 0.85
DecimalFormat mf = new DecimalFormat("#0.000");
String s = mf.format(d); // "0,850"
s = s.replace(',', '.'); // "0.850"
double conv = Double.parseDouble(s); //0.85
//Como pasar del String s = "0.850" -> Double = 0.850?
Your conversion is correct:
I don't see the need to add the decimals that are zero after the decimal point in a value of type double.
If you have decimals at 0 after the decimal point it is as if they do not exist therefore:
If we define a variable with decimals to the right that are zeros, after the decimal point:
the value will always be
0.85
If we define a variable with decimals to the right and there is a number that is not zero, after the decimal point:
then the value would be
0.8500000000001
If you just want to print the value and make sure you have all the decimals you can use setMinimumFractionDigits()
Here you will have a value:
0.850
Actually, there is no such method, because there is a big problem:
double
encoded .For example, using the calculator on this site , the decimal numeral 0.850 corresponds to this binary numeral:
The ellipses indicate that this numeral is repeated (same as 1/3 = 0.33333...). When we remove the ellipses and put the binary numeral on that page for conversion back to decimal, we get:
0.850 has three digits in decimal, but infinitely many in binary. Which means that when we write
double x = 0.850
the value ofx
is not actually 0.850, but a number close to 0.850, which we can't tell if it was originally written as 0.85, 0.850 or 0.8500.If the approximations inherent in the type
double
are unacceptable for some application where decimal numerals need to be represented precisely, useBigDecimal
.