4 Replies - 572 Views - Last Post: 03 October 2014 - 03:10 PM Rate Topic: -----

#1 Falcoshin   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 31-August 14

Trouble with the double variable type

Posted 03 October 2014 - 05:14 AM

I'm not sure why, but whenever I try to get a value out of a double, it only extends to one decimal place. For instance, (825 / 805) would become 1.0000 (after being run through a DecimalFormat object) instead of 1.0248 like I need it to be (and should be if what I know about primitive variable types is right). Why is the double variable type not giving me the precision I want and, more importantly, how do I fix this?
Is This A Good Question/Topic? 0
  • +

Replies To: Trouble with the double variable type

#2 ChrisNt   User is offline

  • cute bug

Reputation: 262
  • View blog
  • Posts: 896
  • Joined: 31-July 13

Re: Trouble with the double variable type

Posted 03 October 2014 - 05:46 AM

If type is double 825 / 805 will have as result 1.0248447204968945 ..
Was This Post Helpful? 0
  • +
  • -

#3 Juliet07   User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 64
  • Joined: 25-September 14

Re: Trouble with the double variable type

Posted 03 October 2014 - 06:06 AM

Type (825.0 / 805.0) to specify that you need the decimal values as well. :)

say you have a variable x
double x = (825.0/805.0);
System.out.println(x);


Was This Post Helpful? 1
  • +
  • -

#4 Koekje   User is offline

  • New D.I.C Head

Reputation: 20
  • View blog
  • Posts: 45
  • Joined: 24-October 13

Re: Trouble with the double variable type

Posted 03 October 2014 - 07:23 AM

It's because 825 and 805 are treated as integer literals, so integer arithmetic happens when you do 825/805, which evaluates to one. Only then will it get cast to a double, resulting in your 1.000000

Juliets fix is a way to overcome this, though you only have to have one double literal. Another way is to just to assign the value to a variable of type double.
Was This Post Helpful? 1
  • +
  • -

#5 Falcoshin   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 31-August 14

Re: Trouble with the double variable type

Posted 03 October 2014 - 03:10 PM

Just tried it and Juliet's suggestion does indeed fix the problem. Thank you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1