-2

I want to set a long number to a double number. The problem is I want to return it as decimal format. For ex: I have a long number

long a = 123456;

then I cast double b = (double) a; Now b show 1.234**E**5. I want b show exactly like a: 123456.0. Don't want "E" here I cast it to String and then agian parse to double. Like this

b = Double.parseDouble(new Long(a).toString()));

Anyone have better idea pls share it to me. Thank you.

Saket Mittal
  • 3,726
  • 3
  • 29
  • 49
  • 2
    Casting is irrelevant. You want *formatting*, as in *string formatting*. – user2864740 Jul 26 '15 at 08:07
  • use DecimalFormat,http://stackoverflow.com/a/8819889/3651739 – Jishnu Prathap Jul 26 '15 at 08:07
  • See http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0?rq=1 , http://stackoverflow.com/questions/8819842/best-way-to-format-a-double-value-to-2-decimal-places?lq=1 , http://stackoverflow.com/questions/12806278/double-decimal-formatting-in-java?rq=1 for ideas – user2864740 Jul 26 '15 at 08:08

1 Answers1

1

No need to cast to long or use toString on Double object.

Just use DescimalFormat:

DecimalFormat f = new DecimalFormat("#.0");
System.out.println(f.format(123456L));

As you can see 123456L is a long numeric value, but it is formatted as you wanted.

Good Luck.

STaefi
  • 4,297
  • 1
  • 25
  • 43
  • It will be formated. But what I want is a double number to return without "E". I used String as a temp. Then parse to double. b = Double.parseDouble(new Long(a).toString())) Your way is use DecimalFormat as a temp, then parse to double. Which way is better – An Tran Jul 26 '15 at 09:57
  • @AnTran: So your question is quite different, because anybody would take your question as formatting the output while printing double values. If your question is about converting the long to double the way is double d = new Double(123456L); If you see the double as ###E## this is the way it is being printed with the default format. But it is a double value. E representation is the format of printing not the value itself. – STaefi Jul 26 '15 at 10:05