Get a simple double view without going through BigDecimal

With a double number in Java, can I get a simple string representation (e.g. 654987 ) instead of a scientific format (e.g. 6.54987E5 )?

Now I know that we can use the BigDecimal.toPlainString() method, but creating a BigDecimal just to get a String (really?) Seems a bit messy and inefficient for me. Does anyone know differently?

+4
source share
3 answers
 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 rounding at all, I would stick with what you suggested, namely (new BigDecimal(d)).toPlainString() .

+4
source

Use DecimalFormat / NumberFormat .

The main use of the examples:

 NumberFormat nf = NumberFormat.getInstance(); output.println(nf.format(myNumber)); 

For DecimalFormat you can pass formatting / locale information for formatting the number. This link is a good guide to using DecimalFormat .

+3
source

You can do it as follows:

 double number = 654987; String plain = String.format("%.0f", number); 
0
source

All Articles