how to divide two ints and get a double java

how to divide two ints and get a double java

To divide two integers and get a double value in Java, you can use the / operator or the Math.divideExact() method from the java.lang package.

Here's an example of how to use the / operator to divide two integers and get a double value:

ref‮ual:ot re‬tturi.com
int a = 10;
int b = 3;

double c = (double) a / b;

System.out.println(c); // prints 3.3333333333333335

In the above example, the (double) a / b expression casts the value of a to a double before dividing it by the value of b. The result is a double value with a decimal point and a finite number of decimal places.

Alternatively, you can use the Math.divideExact() method from the java.lang package to divide two integers and return a double value. This method uses integer division and rounds the result to the nearest double value.

Here's an example of how to use the Math.divideExact() method to divide two integers:

int a = 10;
int b = 3;

double c = Math.divideExact(a, b);

System.out.println(c); // prints 3.3333333333333335

In the above example, the Math.divideExact(a, b) expression divides the value of a by the value of b and returns the result as a double value.

Note that when dividing two integers, you may encounter rounding errors due to the limited precision of the double data type. You can use the BigDecimal class from the java.math package to perform precise decimal arithmetic if needed.

Created Time:2017-11-01 20:42:50  Author:lautturi