Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding negative numbers in Java

Tags:

java

rounding

According to Wikipedia when rounding a negative number, you round the absolute number. So by that reasoning, -3.5 would be rounded to -4. But when I use java.lang.Math.round(-3.5) returns -3. Can someone please explain this?

like image 630
Elie Avatar asked Nov 06 '08 18:11

Elie


People also ask

How do you round negative numbers?

While rounding negative numbers the rounding is done downwards, that is negative numbers are rounded down. If a number such as -2.2 needs to be rounded then the result will be -2 because -2.2 is greater than -2.5 therefore rounded up and result will be -2.

Does Java round 0.5 up or down?

In mathematics, if the fractional part of the argument is greater than 0.5, it is rounded to the next highest integer. If it is less than 0.5, the argument is rounded to the next lowest integer.

What is 1.5 round in Java?

Today I figured out this behavior of Java and Javascript's Math. round function. It makes (1.40) to 1 as well as (-1.40) to -1. It makes (1.60) to 2 as well as (-1.60) to -2. Now, it makes (1.5) to 2.


2 Answers

According to the javadoc

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

Conceptually, you round up. In other words, to the next integer greater than the value and -3 is greater than -3.5, while -4 is less.

like image 97
sblundy Avatar answered Sep 21 '22 21:09

sblundy


There are a variety of methods of rounding; the one you are looking at is called Symmetrical Arithmetic Rounding (as it states). The section you are referring to states: "This method occurs commonly used in mathematical applications, for example in accounting. It is the one generally taught in elementary mathematics classes." This seems to acknowledge that it is not a rule that is globally agreed upon, just the one that is most common.

Personally, I don't recall ever being taught that rule in school. My understanding of rounding has always been that .5 is rounded up, regardless of the sign of the number. Apparently the authors of Java have the same understanding. This is Asymmetrical Arithmetic Rounding.

Different tools and languages potentially use different rounding schemes. Excel apparently uses the symmetric method.

(Overall, I would advise that if you find a conflict between Wikipedia and experience, you look for information elsewhere. Wikipedia is not perfect.)

like image 40
Dave Costa Avatar answered Sep 20 '22 21:09

Dave Costa