convert money in number to words

I'm having trouble of how I would make this program convert decimals into A fraction.

For example:
Enter the dollar amount:$23.45
twenty three and 45/100

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 #include <iostream>
#include <string>
#include <vector>
using namespace std;



vector<string> ones {"","one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
vector<string> teens {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen","sixteen", "seventeen", "eighteen", "nineteen"};
vector<string> tens {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

string nameForNumber (long number)
{
    if (number < 10) {
        return ones[number] ;
    } else if (number < 20) {
        return teens [number - 10];
    } else if (number < 100) {
        return tens[number / 10] + ((number % 10 != 0) ? " " + nameForNumber(number % 10) : "");
    } else if (number < 1000) {
        return nameForNumber(number / 100) + " hundred" + ((number % 100 != 0) ? " " + nameForNumber(number % 100) : "");
    }
    else if (number < 1000000) {
        return nameForNumber(number / 1000) + " thousand" + ((number % 1000 != 0) ? " " + nameForNumber(number % 1000) : "");
    }
    return "error";
}

int main()
{
    long input;
    do
    {
        cout << "Enter the dollar amount: ";
        cin >> input;
        cout << nameForNumber(input) << endl;
    }while (input > 0);
    return 0;
}
You could have the input be a string instead of a long, and the parse the string for the existence of a period separator, and from there use functions like std::atoi or std::stol to convert the left and right to separate integers.
Last edited on
I'm having trouble making the input a string, can you edit my code to show what you mean.
Something quick and dirty using std::trunc on a floating point number (double):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cmath> // std::trunc
#include <iostream>

int main()
{
   double number { 123.45 };

   std::cout << number << '\n';

   double integral { std::trunc(number) };

   std::cout << integral << '\n';

   double fraction { ((number - integral) * 100.0) };

   std::cout << fraction << '\n';

   std::cout << '\n' << integral << " and " << fraction << "/100.\n";
}

123.45
123
45

123 and 45/100.

"Wordizing" a whole number should be easier than dealing with a fraction, if you want 123 to be "one hundred twenty three"
Topic archived. No new replies allowed.