askvity

How to get decimal value in Java after division?

Published in Java Division 2 mins read

To obtain a decimal value after division in Java, you need to ensure that at least one of the operands is a floating-point type (like double or float). If you're dividing two integers, Java performs integer division, which truncates the decimal part. Here's how to get a decimal result:

Casting to Double

The most common approach is to cast either the numerator or the denominator to a double before performing the division. This forces Java to treat the operation as floating-point division.

int a = 55;
int b = 25;
double r = (double) a / b; // The answer is 2.2
System.out.println(r);

In this example, (double) a casts the integer a to a double. Consequently, the division (double) a / b is treated as a floating-point division, resulting in the decimal value 2.2. The same result could be achieved by casting b instead: double r = a / (double) b;

Using Double Literals

Alternatively, you can directly use double literals for one or both of the numbers.

int a = 55;
double b = 25.0; // Or float b = 25.0f;
double r = a / b; // The answer is 2.2
System.out.println(r);

Here, even though a is an integer, dividing it by the double value b will result in a double result.

Table Summarizing Methods

Method Example Result Explanation
Casting Numerator (double) a / b 2.2 Converts the numerator to a double before division.
Casting Denominator a / (double) b 2.2 Converts the denominator to a double before division.
Using Double Literals a / 25.0 2.2 Uses a double literal for the denominator.

Practical Insights

  • Precision: double provides higher precision compared to float. Choose double for most general-purpose calculations unless memory is a significant constraint.
  • Order of Operations: Ensure the cast is applied before the division. (double) (a / b) will first perform integer division and then cast the result to a double, which won't give you the desired decimal value.
  • Variable Type: The variable receiving the result of the division (r in the examples) must be a floating-point type (double or float) to store the decimal value.

Related Articles