programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# decimal values

Greenhorn
Posts: 28
1
• 1

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
• 1
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
• 1
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

i have understood thank you

Marshal
Posts: 56608
172
...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.