I have been having a really hard time trying to get my code to work properly. I need to write a program that takes a number no bigger than 12 digits and converts it into currency format using string manipulation. I feel like I have most of it but I don't know how to get the - sign to be in front of the $ sign and how to get the commas to work when there is no decimal at the end.
Here it is:
/*
I need a 12 digit maximum double precision number
verify that it is a double < 12 digits
verify that all digits are numeric with a possible
minus sign in the first position t
decimal is 2nd or 3rd last digit;
convert the number to currency using string manipulation
with commas placed at 3 digit intervals counted from the decimal
$ in front
- in front of $
0 is a positive number
Display currency format
*/
#include <iostream>
#include <string>
using namespace std;
void dollarFormat(string &);
int main()
{
cout << "Student Name: \t Chad Weireter" << endl
<< "Student ID:900658044" << endl << endl;
string input;
cout << "Please enter a number up to 12 digits long." << endl
<< "The number may be positive or negative" << endl
<< "and may include fractions (Up to two decimal positions)" << endl
<< "Sign and decimal dot(.) are not included in the digit count: ";
cin >> input;
dollarFormat(input);
cout << "The currency value is:\t" << input << endl;
cin.get();
cin.ignore();
}
void dollarFormat(string ¤cy)
{
int dp;
dp = currency.find('.');
if (dp > 3)
{
for (int x = dp - 3; x > 0; x -= 3)
currency.insert(x, ",");
}
currency.insert(0, "$");
}
Minus Sign
For the minus sign... have you considered doing what you did with the find('.')
?
try doing find('-')
.
What index position will the minus sign be in if its a negative number?
Next, if there is a minus sign at that index then should you be inserting the dollar sign at the 0
index... or should you be inserting it somewhere else?
Dollar Sign
When you insert the dollar sign... you need to make a decision here with a control statement... if
positive number then insert the dollar sign at index 0 (like you did already)... else
negative insert the dollar sign at index position... :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.