• Post Reply Bookmark Topic Watch Topic
  • New Topic

decimal values  RSS feed

 
Greenhorn
Posts: 28
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


hello everybody i am a beginner in java i wrote a simple program of addition, subtraction, multiplication and division.
i declared the c value as double as its value is in division also. but am getting only decimal value after point that is 0.0. what should i do to get atleast 3 to 4 values after decimal.

output is
c=0.0
 
Saloon Keeper
Posts: 3330
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you divide an int by an int the divide operation does not result in any decimal values. The result is an int. This is especially noticeable when you have A/B and the value of B is greater than the value of A, the result will be zero.

To get a floating point result one or both operands must be float. E.g.
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
since a and b are both integer types, "a/b" does integer division.  Then that is cast up to a float for the assignment.

You need to cast either a or b (usually you'd see it on the first one) to a float before your division...something like

float c = (float)a/b;

that may not be 100% correct...but it's the basic idea.
 
nicky priya
Greenhorn
Posts: 28
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


i have understood thank you
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and welcome to the Ranch

Use doubles rather than floats. You will have the same problem about having to cast. Or try
1.0 * a / b;
After the 1.0, you will be in the realms of double arithmetic and you will see the fractional value.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!