Skip to content

[Python] 取數值小數點的方法(指定位數、四捨五入)

本來我經營個人網站,主要是寫我自己的學習的筆記,方便我日後自己查看。不過幾個禮拜前,我偶然被一個下班後想要精進、學習寫程式的朋友詢問了:我該如何取得數值的小數點?

那似乎是他上的線上課程的作業。

無獨有偶,昨天我又在自己 WordPress 的後台,看到了:

這時差點笑出聲來。這到底是哪家的作業啊,一直出現。

想了想,我決定掏磚引玉,直接動手寫一些簡單範例。我知道使用 Python 內建的函式才是最快的方法。不過我在想:既然是所謂的『作業』,那應該就是讓人去思考『究竟該如何完成』才對。

在此獻醜了。本文要解決的問題亦是我朋友當初問我的 3 個問題:

  • 取數值的全部小數
  • 取數值的指定位數小數
  • 取數值的指定位數小數(四捨五入)

取小數的方法

在開始之前,我得先說明一件事情:

字串(string)是比浮點數(float)更精確的。這是因為在電腦中浮點數是使用二進制儲存,所以實際上的值可能並不是我們所看到的 0.1(實際上,應該會是 0.xxxxxxxxxxxx 之類的,只是很接近 0.1)。

而現在我們所使用的浮點數,則是著名的 IEEE 754 所規範的格式(詳情可以參考 https://en.wikipedia.org/wiki/IEEE_754)。

以下文章中使用字串str)來處理小數。


狀況一: 取數值的全部小數

這是最單純的一種情況,直接使用字串處理,取出全部小數的部分,並在開頭加上 “0.” 等數值。

# coding: utf-8


def main():
    value = 123.754640

    # Step 1: Convert to string
    ans = str(value)
    print("step 1:", ans)

    # Step 2: Split Integer and Decimal
    ans = ans.split('.')
    print("step 2:", ans)

    # Step 3: Get the Decimal
    ans = "0." + ans[1]
    print("step 3:", ans)


if __name__ == "__main__":
    main()


Output:

step 1: 123.75464
step 2: ['123', '75464']
step 3: 0.75464


狀況二: 取數值的指定位數小數

這是上一種狀況的變形。我們多指定了 p 作為小數位數。

# coding: utf-8


def main():
    value = 123.754640
    p = 3

    # Step 1: Convert to string
    ans = str(value)
    print("step 1:", ans)

    # Step 2: Split Integer and Decimal
    ans = ans.split('.')
    print("step 2:", ans)

    # Step 3: Get the decimal places
    ans = "0." + ans[1][:p]
    print("step 3:", ans)


if __name__ == "__main__":
    main()


Output:

step 1: 123.75464
step 2: ['123', '75464']
step 3: 0.754


狀況三: 取數值的指定位數小數(四捨五入)

狀況三則又是狀況二的變形。我們需要再多取小數一個位數,並判斷最後一位數是否>= 5。

要注意的是,實務上你可能會遇到小數已經沒有下一個位數了,但本範例並沒有加以考慮。

# coding: utf-8


def main():
    value = 123.754640
    p = 3

    # Step 1: Convert to string
    ans = str(value)
    print("step 1:", ans)

    # Step 2: Split Integer and Decimal
    ans = ans.split('.')
    print("step 2:", ans)

    # Step 3: Get the decimal places and the next place
    tail = ans[1][p]
    ans = ans[1][:p]
    print("step 3:", [ans, tail])

    # Step 4: Rounding
    if int(tail) >= 5:
        ans = str(int(ans)+1)

    ans = "0." + ans
    print("step 4:", ans)



if __name__ == "__main__":
    main()


Output:

step 1: 123.75464
step 2: ['123', '75464']
step 3: ['754', '6']
step 4: 0.755

References


Read More

Tags:

Leave a Reply取消回覆

Click to Copy
Exit mobile version