I'm toying with an application that is, roughly speaking, a sort of modeler application for the building industry. In the future I'd like it to be possible for the user to use both SI units and imperial. From what I understand, it's customary in the US building industry to use fractions of inches when specifying measurements, eg 3 1/2" - whereas in SI we'd write 3.5, not 3 1/2. I'm looking for a way to work with these different systems in my software - storing them, doing calculations on them etc, not only parsing what a users enters. It should be able to show the user a measurement in the way he entered it, yet being able to calculate with other measurements - for example add 3 cm to 1 1/2 inch. So if a user draws a length of wall of 5 feet and another one of 3 meters, the total measurement should be shown in the default unit system the user selected.
I'm undecided yet on how much flexibility I should add for entering data for the user; e.g. if he enters 1 foot 14 inches, should it should 2 feet 2 inches the next time the measurement is shown? However before I decide things like that, I'm looking for a way to store measurements in an exact form, which is what my question is about.
I'm using C++ and I've looked at Boost.Units, but that doesn't seem to offer a way to deal with fractions.
The simple option is to convert everything to millimeters, but rounding errors would make it impossible to go back to the exact measurement a user entered (if he entered it in imperial measurements). So I'll need something more complex.
For now I'm using a class that is tentatively named 'Distance' and looks conceptually like this:
class Distance
{
public:
Distance(double value);
// operators +, -, *, /
Distance operator+(const Distance& that);
...etc...
std::string StringForm(); // Returns a textual form of the value
Distance operator=(double value);
private:
<question: what should go here?>
}
This clearly shows where my problems are. The most obvious thing to do would be to have an enum that says whether this Distance is storing SI or imperial units, and have fields (doubles, presumably) that store the meters, centimeters and millimeters if it's in SI units and feet and inches if it's imperial. However this will make the implementation of the class littered with if(SI) else ..., and is very wasteful in memory. Plus I'd have to store a numerator and denominator for the feet and inches to be able to exactly store 1/3", for example.
So I'm looking for general design advice on how I should solve these problems, given my design requirements. Of course if there's a C++ library out there that already does these things, or a library in another language I could look at to copy concepts from, that would be great.