/ javascript

Quickie: round()

Once again, different programming languages give different results. Now let's focus on rounding negative numbers.

Python + PHP

print(round(-1.5)) # -2
print(round(1.5))  # 2
echo round(-1.5) // -2
echo round(1.5)  // 2

JavaScript

console.debug(Math.round(-1.5)); // -1
console.debug(Math.round(1.5)); // 2

Rounding

There are way more rounding methods that we were taught at school.
I will not explain them here, but rather share links with you:

This message was edited, firstly I declared JS negative number rounding incorrent. Then after feedback I read about rounding, so now I don't claim it's wrong. I will just say - be careful with different languages, and check them before you engage in any important math.

Edit 2:
In PHP you can specify which rounding method you want to use (well, I should RTFM next time). It's the 3rd parameter to round function.

Constant Description
PHP_ROUND_HALF_UP Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2.
PHP_ROUND_HALF_DOWN Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.
PHP_ROUND_HALF_EVEN Round val to precision decimal places towards the nearest even value.
PHP_ROUND_HALF_ODD Round val to precision decimal places towards the nearest odd value.

StackOverflow suggests to always convert to positive number, and then multiply with -1, if it was a negative number.

Tags:
#js #javascript #math #round #quickie

TvK

IT and languages. Feel free to be a grammar-nazi and correct my English (or any other language).

Read More