How to obtain the decimal part in Python?

In Python, you can use the int() function to extract the integer part of a decimal number and the % operator to retrieve the decimal part.

Here is an example of how to use it:

import math

# 取小数的整数部分
x = 3.14159
integer_part = int(x)
print(integer_part)  # 输出 3

# 取小数的小数部分
decimal_part = x % 1
print(decimal_part)  # 输出 0.14159

# 使用math模块的floor函数取小数的整数部分
integer_part = math.floor(x)
print(integer_part)  # 输出 3

# 使用math模块的modf函数同时取小数的整数部分和小数部分
integer_part, decimal_part = math.modf(x)
print(integer_part)  # 输出 0.14159
print(decimal_part)  # 输出 3.0

Please note that the above method is only suitable for regular decimals. Precision issues with floating-point numbers may cause inaccuracies when extracting the decimal portion. For cases requiring precise decimal handling, it is recommended to use the decimal module.

bannerAds