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

更新于: 2020年10月6日

327 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.