With a double number in Java, is it possible to get a plain string representation (Eg., 654987
) instead of the scientific format (Eg., 6.54987E5
) ?
Now I know we can use the BigDecimal.toPlainString()
method, but creating a BigDecimal
simply to get a String
(really?) seems a bit sloppy and inefficient to me.
Does anyone know of another way?
double d = 12345678;
System.out.println(d);
System.out.println(String.format("%.0f", d));
1.2345678E7 12345678
Note that if you only need to print this string representation you can simply use System.out.printf("%.0f", d)
.
If you don't want any rounding at all, then I would stick with what you suggested, namely (new BigDecimal(d)).toPlainString()
.
Use DecimalFormat
/ NumberFormat
.
Basic usage from the examples:
NumberFormat nf = NumberFormat.getInstance();
output.println(nf.format(myNumber));
For DecimalFormat
, you can pass in a formatting pattern / locale information for formatting the number. This link is a good tutorial on using DecimalFormat
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With