LinkedIn Reddit icon

Dunder Doc

by Valdir Stumm Jr

Python 3 rounding oddities

Rounding a decimal number with Python 3 is as simple as invoking the round() builtin: >>> round(1.2) 1 >>> round(1.8) 2 We can also pass an extra parameter called ndigits, which defines the precision we want in the result. Such parameter defaults to 0, but we can pass anything: >>> round(1.847, ndigits=2) 1.85 >>> round(1.847, ndigits=1) 1.8 And what happens when we want to round a number like 1.5? Will it round it up or down?