Learn Java Coding

Everything You Have To Know About Java

Rounding

If you want the program to round a number, there are different options. We assume that the variable “number” already contains a number, for example: 123.13698, with type double.

Options To Round on Whole numbers:

  1. In the Print-method

2. With the Math Class

3. Go from double to integer

Round to nearest half:

4. Go from double to integer

 

Explanation:

1. Like we saw before, the print command could round a number. This doesn’t mean that the number is rounded but you give an output number that is rounded.

Example
out.printf("This article will cost %.2f euro", number);

output: 123.14

2. You could use the class Math, this class contains a method that is called “round”. This will round the number you give as input for example.

double rounded = Math.round(number);
out.println(rounded)

output: 123.0

For rounding on whole integers add:

int rounded = (int) Math.round(number);
out.println(rounded);

output: 123

With a little bit of computations could you also round on two decimal places:

double rounded = Math.round(number*100.0)/100.0;
out.print(rounded);

output: 123.14

3. The third option is to go from type double to type int.

int rounded = (int) number;
out.print(rounded);

output: 123

double rounded = ((int) (number * 100.0))/100.0;
out.print(rounded);

output: 123.14

Round to the nearest half

4. So you have a number, let’s call it input. For example, we use the number 5.6.

double number = ((int) (input*2 + 0.5))/2.0;

You do the input times 2, in this case, 11.2. Then plus 0.5, that is 11.7. Then round you round the number down, to 11, like we did in 3. And then divide by 2.0 because you want to make it double again, so use 2.0 instead of 2. If you did 2 instead of 2.0 the outcome was 5 instead of 5.5.

Next Post

Previous Post

© 2024 Learn Java Coding