How often do you round various numbers in your day-to-day job? Do you know what type of rounding do you actually use?

Let’s compare several programming languages and their default (meaning without additional parameters if the rounding function allows it) rounding techniques.

I’ll use two notions of rounding: banker’s rounding and round half up. More info about different techniques can be found on Wikipedia.

.NET

In dotnet (Framework, Core, 5+) banker’s rounding is used by default.

Math.Round(0.5); // 0
Math.Round(1.5); // 2
Math.Round(2.5); // 2
Math.Round(3.5); // 4

If you need round half up, use the following

Math.Round(0.5, MidpointRounding.AwayFromZero); // 1
Math.Round(1.5, MidpointRounding.AwayFromZero); // 2
Math.Round(2.5, MidpointRounding.AwayFromZero); // 3
Math.Round(3.5, MidpointRounding.AwayFromZero); // 4

JavaScript

In JavaScript round half up is used be default.

Math.round(0.5); // 1
Math.round(1.5); // 2
Math.round(2.5); // 3
Math.round(3.5); // 4

Python (2.7, 3+)

In Python 2.7 round half up is used by default.

round(0.5) # 1
round(1.5) # 2
round(2.5) # 3
round(3.5) # 4

But in Python 3+ banker’s rounding is used by default.

round(0.5) # 0
round(1.5) # 2
round(2.5) # 2
round(3.5) # 4

This was quite surprising, to be honest.

Java

In Java (JDK 1.8.0, 9, 10, 11) round half up is used by default.

Math.round(0.5); // 1
Math.round(1.5); // 2
Math.round(2.5); // 3
Math.round(3.5); // 4

Go

In Go round half up is used by default.

math.Round(0.5) // 1
math.Round(1.5) // 2
math.Round(2.5) // 3
math.Round(3.5) // 4

But if you want banker’s rounding there is a default function for this too.

math.RoundToEven(0.5) // 0
math.RoundToEven(1.5) // 2
math.RoundToEven(2.5) // 2
math.RoundToEven(3.5) // 4

PHP

In PHP round half up is used by default.

round(0.5); # 1
round(1.5); # 2
round(2.5); # 3
round(3.5); # 4