1

I'm trying to round my final answer to 2 decimals so it is Dollars and Cents. I'm new to coding, and can't figure it out. I want to round "w" in the line that says "The amount you need to charge is" Here's my code:

#include <iostream>

using namespace std;

int main()
{
    string Choice;


    float x, w;

    cout << "Please enter the amount needed." << endl;
    cin >> x;


    w = x/(1-0.0275);   

    cout << "The amount you need to charge is $"<< w << "." << endl;

    return (0);

}
dmg
  • 7,438
  • 2
  • 24
  • 33
Godzdude
  • 115
  • 1
  • 2
  • 7

3 Answers3

4

According to the example here http://www.cplusplus.com/forum/beginner/3600/ You could use

cout << setprecision(2) << fixed << w << endl;

(fixed is optional)

You will have to #include <iomanip>

As pointed out by Synxis, this will only work for printing the value, it will not change the value held by w

Tim
  • 41,901
  • 18
  • 127
  • 145
2

You can alway multiply your answer x by 100, round, and then divide by 100.

x = (int)(x*100+0.5f);  
x = ( (float)(x) ) / 100.0;   
namu
  • 146
  • 9
1

You could change your monetary unit to "cents" and then divide by 100 to get the dollars and mod 100 to get the cents.

unsigned int money = 152; // USD $1.52

cout << "Money is: " << (money / 100) << "." << (money % 100) << "\n";

This may be more accurate. Search the web for "everything knows floating point".

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154