C++ Currency Number Format Function
Penny for Your ThoughtsGiven a positive integer n representing the amount of cents you have, return the formatted currency amount. For example, given n = 123456, return "1,234.56".
Example 1
Input
n = 132
Output
"1.32"Example 2
Input
n = 2
Output
"0.02"Example 3
Input
n = 100000000
Output
"1,000,000.00"
Format a Currency Number using C++
Although this task may seem simple with the inbuilt function such as printf or the String format (in Python), to implement this number/currency formating it seems not a trival task. First we would need to get the penny part (fraction) by computing the last two digits (remainder by 100). Then we need to group the other digits into three.
We need a string pad function to add the leading zeros for the middle groups and also the penny (up to 2 digits such as 0.01). The most significant group should not add leading zeros. The numbers are separated by comma.
string solve(int n) { auto pad = [](int v, int d) { string ans = std::to_string(v); if (ans.size() < d) { ans = string(d - (int)ans.size(), '0') + ans; } return ans; }; int cents = n % 100; n /= 100; vector<int> groups; while (n > 0) { groups.insert(begin(groups), n % 1000); n /= 1000; } string ans = ""; if (!groups.empty()) { ans += std::to_string(groups[0]); if (groups.size() > 1) { ans += ","; for (int i = 1; i + 1 < groups.size(); ++ i) { ans += pad(groups[i], 3) + ","; } ans += pad(groups.back(), 3); } } else { ans += "0"; } ans += "."; ans += pad(cents, 2); return ans; }
The above C++ function declares a local lambda function using the functional syntax. Then we group the digits into three and put them in the vector. Then we pad each group including the penny part.
--EOF (The Ultimate Computing & Technology Blog) --
Reposted to Computing and Technology
Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com
My contributions
- Steem Blockchain Tools
- Computing & Technology
- Download Youtube Video
- Find Cheap & Bargin VPS: VPS Database
- Online Software and Tools
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
Alternatively, you could proxy to me if you are too lazy to vote! and you can also vote me at the tool I made: https://steemyy.com/witness-voting/?witness=justyy
🈵👏🏻行长~
Thanks!
拍拍
@justyy, When Non Programmers see these kind of Coding Language feels like entered into different universe. Enjoy your Coding World and stay blessed always.