How to take the number after the decimal point in Python

Mondo Education Updated on 2024-01-31

In Python, taking a number after a decimal point usually involves formatting a floating-point number or taking its decimal part. Here are a few common methods:

1.Format with strings

python

num = 3.14159

decimal_part = "".format(num) takes two decimal places.

print(decimal part) output: 314

In this example, we use string formatting to format the number num to a string that retains two decimal places. `"{}:2f"is a formatted string, where {} represents a placeholder and :2f specifies two decimal places.

2.Use the round() function

python

num = 3.14159

decimal part = round(num, 2) takes two decimal places.

print(decimal part) output: 314

The round() function can be used to round a floating-point number to a specified number of decimal places. In this example, we round num to two decimal places.

3.Use mathfloor() or mathceil() function

If you want to take the number after the decimal point (e.g., take 3.).The last two digits of 14159 are 314), you can use mathfloor() or mathceil() function

python

import math

num = 3.14159

decimal_part = math.floor(num * 100) 100 takes two decimal places and rounds down.

print(decimal part) output: 314

Or: python

import math

num = 3.14159

decimal_part = math.ceil(num * 100) 100 takes two decimal places and rounds up.

print(decimal part) output: 315

math.The floor() function rounds the floating-point number down, while mathThe ceil() function rounds up the floating-point number. Both methods can achieve the effect of taking two decimal places. Which one to use depends on whether you want to round or round up.

Related Pages