how to divide a double in java

how to divide a double in java

To divide a double value in Java, you can use the / operator. The / operator performs division and returns the quotient of the division.

Here's an example of how to divide a double value using the / operator:

re‮al:ot ref‬utturi.com
double a = 10.0;
double b = 3.0;

double c = a / b;

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

In the above example, the a / b expression divides the value of a by the value of b and assigns the result to the c variable. The result is a double value with a decimal point and a finite number of decimal places.

You can also 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 double values, 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