# 在 Python 中截斷浮點數

Syed Moiz Haider 2023年1月30日

## 在 Python 中使用 `round()` 函式截斷一個浮點數

`round(number, n)` 函式將數字作為輸入並將其舍入到 `n` 小數位。

``````print(round(1923334567124, 4))
print(round(2345.1252342, 4))
print(round(192.67, 4))
``````

``````1923334567124
2345.1252
192.67
``````

## 在 Python 中使用 `int()` 函式截斷一個浮點數

``````def truncate(num, n):
integer = int(num * (10 ** n)) / (10 ** n)
return float(integer)

print(truncate(1923334567124, 4))
print(truncate(2345.1252342, 4))
print(truncate(192.67, 4))
``````

``````1923334567124.0
2345.1252
192.6699
``````

## 在 Python 中使用 `str()` 函式截斷一個浮點數

``````def truncate(num, n):
temp = str(num)
for x in range(len(temp)):
if temp[x] == ".":
try:
return float(temp[: x + n + 1])
except:
return float(temp)
return float(temp)

print(truncate(1923334567124, 4))
print(truncate(2345.1252342, 4))
print(truncate(192.67, 4))
``````

``````1923334567124.0
2345.1252
192.67
``````

Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.