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