程序在Python中查找给定金额的美分格式化后的金额
假设我们有一个正数n,其中n代表我们拥有的美分量,我们必须找到格式化的货币量。
因此,如果输入类似于n=123456,则输出将为“1,234.56”。
为了解决这个问题,我们将遵循以下步骤-
cents:=n作为字符串
如果分的大小<2,则
返回“0.0”并置分
如果分的大小等于2,则
返回“0”。级联
货币:=分的子字符串,除了最后两位数字
美分:='。'连接最后两位
当货币的大小>3时,
美分:=','连接货币后三位数字
货币:=分的一小串,最后三位除外
美分:=货币并置美分
返仙
让我们看下面的实现以更好地理解-
示例
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