Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round integer in java

Tags:

java

I want to round the number 1732 to the nearest ten, hundred and thousand. I tried with Math round functions, but it was written only for float and double. How to do this for Integer? Is there any function in java?

like image 262
Achaius Avatar asked Apr 25 '11 06:04

Achaius


People also ask

How do you round an integer?

Rounding to the Nearest IntegerIf the digit in the tenths place is less than 5, then round down, which means the units digit remains the same; if the digit in the tenths place is 5 or greater, then round up, which means you should increase the unit digit by one.

How do you round to 2 decimal places in Java?

1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places. For DecimalFormat , the default rounding mode is RoundingMode.

How do you round a value in Java?

round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long. If the argument is NaN, the result is 0.

What is 1.5 round in Java?

round(1.5) will return 2 hence 2 is closer to +∞ while comparing with 1. Similarly Math. round(-1.5) will return -1 hence -1 is closer to +∞ while comparing with -2.


2 Answers

What rounding mechanism do you want to use? Here's a primitive approach, for positive numbers:

int roundedNumber = (number + 500) / 1000 * 1000; 

This will bring something like 1499 to 1000 and 1500 to 2000.

If you could have negative numbers:

int offset = (number >= 0) ? 500 : -500; int roundedNumber = (number + offset) / 1000 * 1000; 
like image 136
EboMike Avatar answered Sep 20 '22 17:09

EboMike


(int)(Math.round( 1732 / 10.0) * 10) 

Math.round(double) takes the double and then rounds up as an nearest integer. So, 1732 will become 173.2 (input parameter) on processing by Math.round(1732 / 10.0). So the method rounds it like 173.0. Then multiplying it with 10 (Math.round( 1732 / 10.0) * 10) gives the rounded down answer, which is 173.0 will then be casted to int.

like image 42
ilalex Avatar answered Sep 24 '22 17:09

ilalex