用 Python 编写程序,查找给定金额的格式化美分金额

pythonserver side programmingprogramming更新于 2026/1/12 6:36:17

假设我们有一个正数 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

相关文章


有用资源