Java double Example

Have you ever met the situation that you get an integer but you really want a double?

For the following method, devide(2,3) will return 0.0.

public static double devide(int x, int y){
	return x/y;
}

The problem is that x/y does int division. If you want it to do double division, you can cast one of the operands. Both (double)x/y and x/(double)y will work.

public static double devide(int x, int y){
	return (double)x/y;
}

Very often you may want to round a double number. There are multiple ways to do it and the following is a commonly used simple method. If you want to round the result to 2 digits, you can use the following code:

public static double divide(int x, int y){
	double z= (double)x/y;
	double pro = Math.round(z * 100);
	return pro/100;
}

4 thoughts on “Java double Example”

Leave a Comment