- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find the formatted amount of cents of given amount in Python
Suppose we have a positive number n, where n is representing the amount of cents we have, we have to find the formatted currency amount.
So, if the input is like n = 123456, then the output will be "1,234.56".
To solve this, we will follow these steps −
- cents := n as string
- if size of cents < 2, then
- return '0.0' concatenate cents
- if size of cents is same as 2, then
- return '0.' concatenate cents
- currency := substring of cents except last two digits
- cents := '.' concatenate last two digit
- while size of currency > 3, do
- cents := ',' concatenate last three digit of currency concatenate cents
- currency := substring of cents except last three digits
- cents := currency concatenate cents
- return cents
Let us see the following implementation to get better understanding −
Example
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))
Input
523644
Output
5,236.44
Advertisements