I tried many ways to convert a Double to it's exact decimal String with String.format() and DecimalFormater and I found this so far :
String s = "-.0000000000000017763568394002505";
Double d = Double.parseDouble(s) * 100;
System.out.println((new java.text.DecimalFormat("###########################.################################################################################")).format(d));
(https://ideone.com/WG6zeC)
I'm not really a fan of my solution because it's ugly to me to make a huge pattern that does not covers all the cases.
Do you have another way to make this ?
I really want to have ALL the decimals, without scientific notation, without trailing zeros.
Thanks
P.S.: I need this without external libraries and in Java 1.7.
Seems as if you have to deal with some precision. double is not intended for this use. Better use BigDecimal
String value="13.23000";
BigDecimal bigD=new BigDecimal(value);
System.out.println(bigD);
System.out.println(bigD.stripTrailingZeros().toPlainString());
There is a big difference between new BigDecimal("0.1")
and new BigDecimal(0.1)
. Using the String constructor can result in trailing zeros, and loses the effects of rounding to double on parsing the string. If the objective is to print the exact value of the double, you need to use BigDecimal's double constructor. Do any arithmetic in double, not BigDecimal.
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
String s = "-.0000000000000017763568394002505";
double d = Double.parseDouble(s) * 100;
System.out.println(new BigDecimal(d).toPlainString());
}
}
Try this code:
You can also use toString() method, but it uses scientific notation.
https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#toPlainString()
BigDecimal bd = new BigDecimal("-.0000000000000017763568394002505");
System.out.println(bd.toPlainString());