[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 306
  • Last Modified:

Detect no input or 0, display only 2 decimal places

Below is my mortgage program. I am having a couple of issues. The payment amount usually displays correctly, but in some cases it displays too many decimal places. If I use a loan of 10,000, 10 yrs, ad 9% iterest it displays 3 decimal places. I would like to make it always only display 2. Also, I am looking for a way to detect no input or 0, and display a message to try again. Any assistance would be appreciated.

My code

#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL)
{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
break; //valid, stop loop
}
}

return n;
}
// function to validate interest rate
double read_double()
{

string s;
double d = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
d = strtod(s.c_str(), &pCnvEnd);
if (*pCnvEnd != NULL)
{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
break; //valid, stop loop
}
}

return d;
}
// get user inputs and validate
void getInput(double &loanAmount, int &termYears, double &interestRate){

cout << "\t\t\tJon's Mortgage Calculator" << endl << endl;
// Calculator Title
cout << "\n\n \t\t\t Loan amount: $"; // ask user for loan amount
loanAmount = read_double(); // capture loan amount
cout << "\n\n \t\t\t Loan Term In Years: "; // ask user for loan term
termYears = read_int(); // capture loan term
cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
interestRate = read_double(); // capture interest rate

}

// function to print amortization table
void printLoanPayments(int payment, double loanBalance, double monthlyPrinciple, double monthlyInterest){
  // print verbage and data values
   cout << " " << setw(15) << setprecision(2) << payment;
   cout << " " << setw(15) << fixed << setprecision(2) << fabs(loanBalance);
   cout << " " << setw(15) << fixed << setprecision(2) << monthlyPrinciple;
   cout << setw(15) << fixed << setprecision(2) << monthlyInterest << endl;
}

void computeMortgage(double &loanAmount, int &termYears, double &interestRate){
   int payment = 0; // payment incrementor
   int termMonths; // term in months
   double monthlyPayment; // monthly payment

   double monthlyInterest; // vaiable to hold monthly interest paid
   double loanBalance; // variable to hold descending loan balance
   int months = 0; // month incrementor
   double monthlyPrinciple; // variable to hold monthly principle paid
   int lineCount = 1; // variable to count lines for screen pause
   double interestRateMonthly; //
   
   //calculate term in years and monthly interest rate
   interestRateMonthly = ((interestRate / 12) / 100);
   termMonths = (termYears *12);

   //calculate mothly payment
   monthlyPayment = (loanAmount *interestRateMonthly) / (1-pow(1.0 / (1.0 +
   interestRateMonthly), termMonths));

   //display monthly payment to the screen.
   cout << "\n\n \t\t\t Monthly Payment $" << monthlyPayment  << endl << endl;

  loanBalance = loanAmount; // set initial loan balance to loan amount

  // create headings and separator line
  cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
  cout << "\t -------------------------------------------------------------" << endl;

  while (loanBalance >= 0.01) //Loop ends when loan is below one penny

  {
    monthlyInterest = (loanBalance *interestRateMonthly);
    // calculate monthly interest
    monthlyPrinciple = monthlyPayment - monthlyInterest;
    // calculate monthly principle
    loanBalance = loanBalance - monthlyPrinciple; // calculate loan balance
    loanAmount = loanBalance; // assign new balance ot loan amount
    payment++; // increment payment number

   // print verbage and data values
   printLoanPayments(payment, loanBalance, monthlyPrinciple, monthlyInterest);

   loanBalance = loanAmount; // assign remaining balance to loan balance
   lineCount++; // increment line counter

   // count for payment printed to screen
   if (lineCount > 20)
     {
         //pause displays a message and waits for the user to hit a key
         system("PAUSE");
         lineCount = 0; // Reset line counter

        // reprint headings
        cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
        cout << "\t -------------------------------------------------------------" << endl;

       }
    }
  }
int main()
{

//declare variables

double loanAmount; // loan amount
double interestRate; // interest rate
char again = '0'; // NOT int again = 0;
int termYears; // term of loan in years
do
// Loop to allow the user another calculation
{
  getInput(loanAmount, termYears,interestRate);
  computeMortgage(loanAmount,termYears,interestRate);
// Offer the user another calculation
cout << (
"\n\n\t Enter 1 to calculate another mortgage, any other key to quit ");
cin >> again; // capture response for another calculation
system("cls"); // clear the screen
}
while (again == '1') // End of loop for another go.
;

return 0;
}
0
ghost8067
Asked:
ghost8067
  • 5
  • 4
  • 2
  • +1
2 Solutions
 
Infinity08Commented:
If you want to limit it to two decimal places, you can use  << fixed << setprecision(2) just like you did elsewhere in the code.
0
 
jkrCommented:
And to detect '0', test for that value in your input function:

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL)
{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (n == 0)
cout << "Not a valid number, please re-enter a non-null value" << " ";
else break; //valid and non-zero input, stop loop <------------------
}
}
0
 
UrosVidojevicCommented:
For detecting no input or 0, you will need to write function

int getNumbet();

that read char by char until the end of line.
Then trim string read in that way.
If the result is "0" or "" that function should return some special value (for example negative value).
else it should return read value converted from string to int.

If you need more help on this, just ask.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ghost8067Author Commented:
Thanks, that worked fine. I was forgetting to include the fixed statement.
0
 
ghost8067Author Commented:
I now have a successful check for 0's on all 3 fields ad the decimal displaying 2 places. If ayone has an idea to detect nothing entered, it would be appreciated.
0
 
jkrCommented:
That would be

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also
{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (n == 0)
cout << "Not a valid number, please re-enter a non-null value" << " ";
else break; //valid and non-zero input, stop loop <------------------
}
}
0
 
ghost8067Author Commented:
I gave that a try. Cursor sits there as before without displaying the error message. The code is below

#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also

{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (n == 0)
cout << "Please enter a non-zero value " << " ";
else break; //valid and non-zero input, stop loop <------------------
}
}
return n;
}
// function to validate interest rate
double read_double()
{

string s;
double d = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
d = strtod(s.c_str(), &pCnvEnd);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also

{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (d == 0)
cout << "Please enter a non-zero value " << " ";
else break; //valid and non-zero input, stop loop <------------------

}
}

return d;
}
// get user inputs and validate
void getInput(double &loanAmount, int &termYears, double &interestRate){

cout << "\t\t\tJon's Mortgage Calculator" << endl << endl;
// Calculator Title
cout << "\n\n \t\t\t Loan amount: $"; // ask user for loan amount
loanAmount = read_int(); // capture loan amount
cout << "\n\n \t\t\t Loan Term In Years: "; // ask user for loan term
termYears = read_int(); // capture loan term
cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
interestRate = read_double(); // capture interest rate

}

// function to print amortization table
void printLoanPayments(int payment, double loanBalance, double monthlyPrinciple, double monthlyInterest){
  // print verbage and data values
   cout << " " << setw(15) << setprecision(2) << payment;
   cout << " " << setw(15) << fixed << setprecision(2) << fabs(loanBalance);
   cout << " " << setw(15) << fixed << setprecision(2) << monthlyPrinciple;
   cout << setw(15) << fixed << setprecision(2) << monthlyInterest << endl;
}

void computeMortgage(double &loanAmount, int &termYears, double &interestRate){
   int payment = 0; // payment incrementor
   int termMonths; // term in months
   double monthlyPayment; // monthly payment

   double monthlyInterest; // vaiable to hold monthly interest paid
   double loanBalance; // variable to hold descending loan balance
   int months = 0; // month incrementor
   double monthlyPrinciple; // variable to hold monthly principle paid
   int lineCount = 1; // variable to count lines for screen pause
   double interestRateMonthly; //
   
   //calculate term in years and monthly interest rate
   interestRateMonthly = ((interestRate / 12) / 100);
   termMonths = (termYears *12);

   //calculate mothly payment
   monthlyPayment = (loanAmount *interestRateMonthly) / (1-pow(1.0 / (1.0 +
   interestRateMonthly), termMonths));

   //display monthly payment to the screen.
   cout << "\n\n \t\t\t Monthly Payment $" << fixed << setprecision(2) << monthlyPayment  << endl << endl;

  loanBalance = loanAmount; // set initial loan balance to loan amount

  // create headings and separator line
  cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
  cout << "\t -------------------------------------------------------------" << endl;

  while (loanBalance >= 0.01) //Loop ends when loan is below one penny

  {
    monthlyInterest = (loanBalance *interestRateMonthly);
    // calculate monthly interest
    monthlyPrinciple = monthlyPayment - monthlyInterest;
    // calculate monthly principle
    loanBalance = loanBalance - monthlyPrinciple; // calculate loan balance
    loanAmount = loanBalance; // assign new balance ot loan amount
    payment++; // increment payment number

   // print verbage and data values
   printLoanPayments(payment, loanBalance, monthlyPrinciple, monthlyInterest);

   loanBalance = loanAmount; // assign remaining balance to loan balance
   lineCount++; // increment line counter

   // count for payment printed to screen
   if (lineCount > 20)
     {
         //pause displays a message and waits for the user to hit a key
         system("PAUSE");
         lineCount = 0; // Reset line counter

        // reprint headings
        cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
        cout << "\t -------------------------------------------------------------" << endl;

       }
    }
  }
int main()
{

//declare variables

double loanAmount; // loan amount
double interestRate; // interest rate
char again = '0'; // NOT int again = 0;
int termYears; // term of loan in years
do
// Loop to allow the user another calculation
{
  getInput(loanAmount, termYears,interestRate);
  computeMortgage(loanAmount,termYears,interestRate);
// Offer the user another calculation
cout << (
"\n\n\t Enter 1 to calculate another mortgage, any other key to quit ");
cin >> again; // capture response for another calculation
system("cls"); // clear the screen
}
while (again == '1') // End of loop for another go.
;

return 0;
}
0
 
ghost8067Author Commented:
Sorry, I posted the old code. Here it is with the changes.

#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also

{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (n == 0)
cout << "Please enter a non-zero value " << " ";
else break; //valid and non-zero input, stop loop <------------------
}
}
return n;
}
// function to validate interest rate
double read_double()
{

string s;
double d = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
d = strtod(s.c_str(), &pCnvEnd);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also

{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (d == 0)
cout << "Please enter a non-zero value " << " ";
else break; //valid and non-zero input, stop loop <------------------

}
}

return d;
}
// get user inputs and validate
void getInput(double &loanAmount, int &termYears, double &interestRate){

cout << "\t\t\tJon's Mortgage Calculator" << endl << endl;
// Calculator Title
cout << "\n\n \t\t\t Loan amount: $"; // ask user for loan amount
loanAmount = read_int(); // capture loan amount
cout << "\n\n \t\t\t Loan Term In Years: "; // ask user for loan term
termYears = read_int(); // capture loan term
cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
interestRate = read_double(); // capture interest rate

}

// function to print amortization table
void printLoanPayments(int payment, double loanBalance, double monthlyPrinciple, double monthlyInterest){
  // print verbage and data values
   cout << " " << setw(15) << setprecision(2) << payment;
   cout << " " << setw(15) << fixed << setprecision(2) << fabs(loanBalance);
   cout << " " << setw(15) << fixed << setprecision(2) << monthlyPrinciple;
   cout << setw(15) << fixed << setprecision(2) << monthlyInterest << endl;
}

void computeMortgage(double &loanAmount, int &termYears, double &interestRate){
   int payment = 0; // payment incrementor
   int termMonths; // term in months
   double monthlyPayment; // monthly payment

   double monthlyInterest; // vaiable to hold monthly interest paid
   double loanBalance; // variable to hold descending loan balance
   int months = 0; // month incrementor
   double monthlyPrinciple; // variable to hold monthly principle paid
   int lineCount = 1; // variable to count lines for screen pause
   double interestRateMonthly; //
   
   //calculate term in years and monthly interest rate
   interestRateMonthly = ((interestRate / 12) / 100);
   termMonths = (termYears *12);

   //calculate mothly payment
   monthlyPayment = (loanAmount *interestRateMonthly) / (1-pow(1.0 / (1.0 +
   interestRateMonthly), termMonths));

   //display monthly payment to the screen.
   cout << "\n\n \t\t\t Monthly Payment $" << fixed << setprecision(2) << monthlyPayment  << endl << endl;

  loanBalance = loanAmount; // set initial loan balance to loan amount

  // create headings and separator line
  cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
  cout << "\t -------------------------------------------------------------" << endl;

  while (loanBalance >= 0.01) //Loop ends when loan is below one penny

  {
    monthlyInterest = (loanBalance *interestRateMonthly);
    // calculate monthly interest
    monthlyPrinciple = monthlyPayment - monthlyInterest;
    // calculate monthly principle
    loanBalance = loanBalance - monthlyPrinciple; // calculate loan balance
    loanAmount = loanBalance; // assign new balance ot loan amount
    payment++; // increment payment number

   // print verbage and data values
   printLoanPayments(payment, loanBalance, monthlyPrinciple, monthlyInterest);

   loanBalance = loanAmount; // assign remaining balance to loan balance
   lineCount++; // increment line counter

   // count for payment printed to screen
   if (lineCount > 20)
     {
         //pause displays a message and waits for the user to hit a key
         system("PAUSE");
         lineCount = 0; // Reset line counter

        // reprint headings
        cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
        cout << "\t -------------------------------------------------------------" << endl;

       }
    }
  }
int main()
{

//declare variables

double loanAmount; // loan amount
double interestRate; // interest rate
char again = '0'; // NOT int again = 0;
int termYears; // term of loan in years
do
// Loop to allow the user another calculation
{
  getInput(loanAmount, termYears,interestRate);
  computeMortgage(loanAmount,termYears,interestRate);
// Offer the user another calculation
cout << (
"\n\n\t Enter 1 to calculate another mortgage, any other key to quit ");
cin >> again; // capture response for another calculation
system("cls"); // clear the screen
}
while (again == '1') // End of loop for another go.
;

return 0;
}
0
 
jkrCommented:
Um, I forgot, 'cin' won't let you enter an empty string anyway...
0
 
jkrCommented:
Hm, try

getline(cin,s);

instead of

cin >> s;
0
 
ghost8067Author Commented:
Thanks for the help. I gave more of the points to jkr. It was the more difficult problem of the 2 .
0
 
Infinity08Commented:
>> I gave more of the points to jkr. It was the more difficult problem of the 2 .

No problem - he deserves it. For some reason, I missed your second question - otherwise I would have answered it too heh. I need new glasses ;)
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 5
  • 4
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now