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;
Category >> Basics  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. ccna training in pune on 2016-11-19

    Thanks for posting this useful content, Let me share this, . CCNA training in pune

  2. sivanesan M on 2017-4-4

    Thank you so much for sharing such a wonderful information.

Leave a comment