Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a plain-string representation of a double without going through BigDecimal

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?

like image 962
user1508893 Avatar asked Jan 11 '13 22:01

user1508893


2 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 any rounding at all, then I would stick with what you suggested, namely (new BigDecimal(d)).toPlainString().

like image 124
arshajii Avatar answered Sep 30 '22 01:09

arshajii


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.

like image 21
Krease Avatar answered Sep 30 '22 01:09

Krease