Float numbers are used to represent the real numbers with integers and decimal parts. Python represents such numbers with 64-bit precision giving it a

How to round to 2 decimals in Python

submited by
Style Pass
2021-05-21 14:20:40

Float numbers are used to represent the real numbers with integers and decimal parts. Python represents such numbers with 64-bit precision giving it a range of almost 1.8 x 10^308.

The methods discussed here can round up float values to our desired decimal places. However, our examples will round them to 2 decimal places. Table of ContentsUsing the round() functionUsing the format() functionUsing the % formattingUsing the f-stringsUsing the math.ceil() and math.floor() functions Using the round() function

The round function is used traditionally to round up numbers to the specified decimal places. We can specify the total digits required after the decimal point in the function itself.

In the above code, we rounded a floating number to two decimal places. If we need to round the number to 2 decimal places and the number has less than 2 decimal places then the number itself gets returned.

We can format strings in Python using many methods to get the final result in our desired format. The format() function is one such way in which we can achieve this.

Leave a Comment