Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.)

For what it's worth, java.math.BigDecimal has selectable rounding modes if you need more control over that sort of thing.

The Wikipedia article you cite does not say that's the only way to round, just the common way to round. Also mentioned in that article are several alternatives (unfortunately none of which describe Java's rounding method - even though they call it out as "Asymmetric Arithmetic Rounding" when indicating what JavaScript does).

You need to decide how you want your numbers rounded, then use that method. If Java's implementation matches that, then great. otherwise you'll need to implement it on your own.

According to Javadocs:

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)

Turns out the convention is to round up. I guess Wikipedia is fallible. Turns out Microsoft got it wrong, though, as they round it to -4 as well, which is not convention (I checked with someone who has a PhD in math).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top