El Spiffy
El Spiffy

Reputation: 135

Currency Formatting C++

So I am trying to create a program that will take a value from the user and convert it to currency formatting (US: $ ). I seem to be almost there, the only issue I am having is that when I input a value without a decimal, it does not format it with the commas. How can I change his function so that it will format it no matter if there is a decimal point or not.

void dollarFormat(string &currency)
{
    int decimal;
    decimal = currency.find('.'); // Find decimal point
    if (decimal > 3) // Insert commas
    {
        for (int x = decimal - 3; x > 0; x -= 3)
            currency.insert(x, ",");
    }
    currency.insert(0, "$"); // Insert dollar sign
}

Upvotes: 1

Views: 1663

Answers (1)

vsoftco
vsoftco

Reputation: 56547

Do a test for std::string::npos:

void dollarFormat(std::string &currency)
{
    auto decimal = currency.find('.');  // find decimal point
    if(decimal == std::string::npos)    // no decimal point
        decimal = currency.length();    
    if (decimal > 3) // Insert commas
    {
        for (auto x = decimal - 3; x > 0; x -= 3)
            currency.insert(x, ",");
    }
    currency.insert(0, "$"); // Insert dollar sign
}

Side note: to make your code portable, make sure you use std::string::size_type as the type of decimal instead of int. Or, even better, use auto type deduction:

auto decimal = currency.find('.');

Upvotes: 3

Related Questions