C++ Currency Number Format Function

in programming •  4 years ago 
Penny for Your Thoughts

Given 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

Support me

If you like my work, please:

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
  ·  4 years ago 

Thanks!

Trade on all cryptocurrency exchanges from one interface! - https://kintum.io/
Trade on all cryptocurrency exchanges from one interface! - https://kintum.io/
Trade on all cryptocurrency exchanges from one interface! - https://kintum.io/

  ·  4 years ago 

拍拍

@justyy, When Non Programmers see these kind of Coding Language feels like entered into different universe. Enjoy your Coding World and stay blessed always.