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?
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With