Python程式:查詢給定金額的格式化美分
假設我們有一個正數 n,其中 n 表示我們擁有的美分數量,我們需要找到格式化的貨幣金額。
因此,如果輸入類似於 n = 123456,則輸出將為“1,234.56”。
為了解決這個問題,我們將遵循以下步驟:
- cents := n 轉換為字串
- 如果 cents 的長度 < 2,則
- 返回 '0.0' 連線 cents
- 如果 cents 的長度等於 2,則
- 返回 '0.' 連線 cents
- currency := cents 去掉最後兩位數字的子字串
- cents := '.' 連線最後兩位數字
- 當 currency 的長度 > 3 時,執行以下操作
- cents := ',' 連線 currency 的最後三位數字連線 cents
- currency := cents 去掉最後三位數字的子字串
- cents := currency 連線 cents
- 返回 cents
讓我們看看下面的實現以獲得更好的理解:
示例
class Solution: def solve(self, n): cents = str(n) if len(cents) < 2: return '0.0' + cents if len(cents) == 2: return '0.' + cents currency = cents[:-2] cents = '.' + cents[-2:] while len(currency) > 3: cents = ',' + currency[-3:] + cents currency = currency[:-3] cents = currency + cents return cents ob = Solution() print(ob.solve(523644))
輸入
523644
輸出
5,236.44
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP