hi, i am writing a program that keeps track of the money in my debit card account. i need the program to be able to pull out a value (such as 1.56356) from a text file, round it to the nearest hundredth, and put it back into the file. any solutions?

Featured Replies in this Discussion

• All you need is to rewrite the value with 2 digit precision after the dot. Look at ... . There are examples that do exactly what you need. Just read the numbers from the input file, and write them to the output file with the setprecision functionality.
Post Contains: Links

Check this out:

``````#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double val_1 = 1.56356;
double val_2 = 1.56756;

cout << floor( (val_1 + 0.005) * 100.0 ) / 100.0 << endl;
cout << floor( (val_2 + 0.005) * 100.0 ) / 100.0 << endl;

return 0;
}``````

Useful link -> http://cplusplus.com/reference/clibrary/cmath/floor/

Another way:

``````#include <iostream>

using namespace std;

int main()
{
double val_1 = 1.56356;
double val_2 = 1.56756;

cout << int( (val_1 + 0.005) * 100.0 ) / 100.0 << endl;
cout << int( (val_2 + 0.005) * 100.0 ) / 100.0 << endl;

return 0;
}``````

All you need is to rewrite the value with 2 digit precision after the dot.

Look at setprecision. There are examples that do exactly what you need.

Just read the numbers from the input file, and write them to the output file with the setprecision functionality.

Check this out:

``````#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double val_1 = 1.56356;
double val_2 = 1.56756;

cout << floor( (val_1 + 0.005) * 100.0 ) / 100.0 << endl;
cout << floor( (val_2 + 0.005) * 100.0 ) / 100.0 << endl;

return 0;
}``````

Useful link -> http://cplusplus.com/reference/clibrary/cmath/floor/

Another way:

``````#include <iostream>

using namespace std;

int main()
{
double val_1 = 1.56356;
double val_2 = 1.56756;

cout << int( (val_1 + 0.005) * 100.0 ) / 100.0 << endl;
cout << int( (val_2 + 0.005) * 100.0 ) / 100.0 << endl;

return 0;
}``````

that got it working perfectly. thank you.

Question Answered as of 4 Years Ago by m4ster_r0shi and mike_2000_17

Lol... Glad to be of help, but the way mike suggested is simpler...

``````#include <iostream>

using namespace std;

int main()
{
double val_1 = 1.56356;
double val_2 = 1.56756;

cout.flags(ios::fixed);
cout.precision(2);

cout << val_1 << endl;
cout << val_2 << endl;

return 0;
}``````
You
This question has already been solved: Start a new discussion instead
Post:
View similar articles that have also been tagged: