E
Eric Lilja
Hi, I need to implement a function that should take a double and split
it into two integers. The decimalpart may be 0 but it may not be
greater than 0.99 and not less than 0.01. In other words, decimalparts
larger than three decimals are invalid input. I know floating point
numbers are not represented exactly in computers so this is tricky
business. This seems to work on my laptop, it's to be used by students
in an assignment to write a monetary class so it mustn't be perfect,
but I would like to hear your input.
#include <cmath>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
void split_double(const double num, int& integer, int& decimals)
{
const int precision = 2;
double d1, d2;
d1 = modf(num, &d2);
if(d1 != 0.0f && (d1 > 0.99f || d1 < 0.01f))
cout << "d1 = " << d1 << " Error!" << endl; // TODO: Throw
exception
stringstream ss;
ss << fixed << setprecision(precision) << num;
ss >> integer;
ss.ignore();
ss >> decimals;
}
int main()
{
int intpart;
int decpart;
split_double(3.99, intpart, decpart);
cout << intpart << "." << decpart << endl;
split_double(3.991, intpart, decpart);
cout << intpart << "." << decpart << endl;
split_double(3.001, intpart, decpart);
cout << intpart << "." << decpart << endl;
}
$ ./foo.exe
3.99
d1 = 0.991 Error!
3.99
d1 = 0.001 Error!
3.0
it into two integers. The decimalpart may be 0 but it may not be
greater than 0.99 and not less than 0.01. In other words, decimalparts
larger than three decimals are invalid input. I know floating point
numbers are not represented exactly in computers so this is tricky
business. This seems to work on my laptop, it's to be used by students
in an assignment to write a monetary class so it mustn't be perfect,
but I would like to hear your input.
#include <cmath>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
void split_double(const double num, int& integer, int& decimals)
{
const int precision = 2;
double d1, d2;
d1 = modf(num, &d2);
if(d1 != 0.0f && (d1 > 0.99f || d1 < 0.01f))
cout << "d1 = " << d1 << " Error!" << endl; // TODO: Throw
exception
stringstream ss;
ss << fixed << setprecision(precision) << num;
ss >> integer;
ss.ignore();
ss >> decimals;
}
int main()
{
int intpart;
int decpart;
split_double(3.99, intpart, decpart);
cout << intpart << "." << decpart << endl;
split_double(3.991, intpart, decpart);
cout << intpart << "." << decpart << endl;
split_double(3.001, intpart, decpart);
cout << intpart << "." << decpart << endl;
}
$ ./foo.exe
3.99
d1 = 0.991 Error!
3.99
d1 = 0.001 Error!
3.0