Skip to content Skip to sidebar Skip to footer

Format Method And Rounding Number

I don't understand how format & rounding numbers works, because for instance: '{:.0f}'.format(234.50) # returns 234 '{:.0f}'.format(235.50) # returns 236 '{:.0f}'.format(236.50

Solution 1:

Python rounds to nearest integer, but if the decimal is 0.5 it rounds to nearest even integer. This method is called round half to even and is common in many programming languages.

This is confirmed in the documentation of the round function as well.

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if called with one argument, otherwise of the same type as number.

For a general Python object number, round(number, ndigits) delegates to number.__round__(ndigits).

Post a Comment for "Format Method And Rounding Number"