Monday, April 25, 2005

Rounding numbers in Java

java.lang.Math class has a static method round() which accepts float and double values as a parameter and returns respectively int and long values.

For example, you have a number 3.1415 and want to round it to the nearest integer. Here's the Java code:

float pi = 3.1415f;
int rounded = Math.round(pi);

Note that when you write 3.1415, you actually write it as 3.1415f. This is because Java treats any decimal constant you write into your code as type double by default, and you must include a trailing 'f' if you wish the number to be treated as type float.

Feel free to post your questions or comments.

3 Comments:

At 29 April, 2005 12:25, Anonymous Anonymous said...

o aciu kos saunus puslapis :)))

 
At 06 January, 2010 23:20, Anonymous Anonymous said...

Hello!!!! Please, help, I need example of code for rounding integers in java. Example: I have "9" I want to get "10" by rounding.

 
At 18 July, 2012 13:27, Anonymous Anonymous said...

How can I do this: i want to round any digit number by two digit.
If the 3rd digit after the decimal is greater than or equal to 5 then I round up. Otherwise, I round down.
Examples:
11.559 -> 11.56
11.555 -> 11.56
11.554 -> 11.55

Please help me, thank a lot

 

Post a Comment

<< Home