1.11M Members

DEV-C++ double rounding help

 
0
 

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?

 
0
 

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;
}
 
1
 

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.

 
0
 

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 3 Years Ago by m4ster_r0shi and mike_2000_17
 
0
 

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:
Start New Discussion
View similar articles that have also been tagged: