I meant get a library that has classes that represent decimal. Sorry I didn't answer that. BTW, java/c# have that built in
An other possible solution could be to store for each instrument its specific price step size. And represent the price as a multiple of this step size. The multiple is an integer, without rounding issues.
In my opinion there is nothing better than my utterly beloved int64_t with fixed decimal points on a per "instrument" basis. You can get most of "instruments" with 6 decimals. I recommend to read http://www.nanex.net/downloads/APIDocs/NxCoreAPIDocs_V21_20100212.zip "concept prices" For your purposes you could simply define a "price type" available of each "instrument"
Funny you should mention this! That's the type that I used to build the class; great minds think alike Note that I'm not sold on this exact implementation of price. Noting your comment regarding fixing decimal places per instrument, I've tried storing the number of decimal places in the private place_ property. Code: // price.h #ifndef _RITCHIE_PRICE_ #define _RITCHIE_PRICE_ #include <iostream> #include <iomanip> #include <cstdint> #include <string> #include <cmath> class Price { public: Price():price_(100), place_(2) {}; Price(int64_t price, int place):price_(price), place_(place) {}; Price(const Price & rhs) { price_ = rhs.price_; place_ = rhs.place_; } long double price()const { return (static_cast<long double> (price_)/pow(10, place_)); } //getter void setPrice(int64_t price, int place) { price_ = price; place_ = place; } private: int64_t price_; int place_; }; #endif int main() { Price aaa(9835, 2); Price bbb(11129835, 5); Price ccc(1200078125, 7); Price ddd; std::cout << "$ " << aaa.price() << "\t\t" << "equity price" << std::endl; std::cout << std::setprecision(5); std::cout << "$ " << bbb.price() << "\t" << "forex price" << std::endl; std::cout << std::setprecision(7); std::cout << "$ " << ccc.price() << "\t" << "bond price" << std::endl; std::cout << std::setprecision(2); std::cout << "$ " << ddd.price() << "\t\t" << "default price" << std::endl; std::cout << std::endl; std::cout << "Press enter to quit."; std::cin.get(); std::cout << std::endl; return 0; } /* OUTPUT $ 98.35 equity price $ 111.29835 forex price $ 120.0078125 bond price $ 1.00 default price */
What your code does not check for is whether the given price is a valid price. For example your forex example would allow a price step of 0.00001, whereas in reality maybe only a multiple of 0.00005 is allowed. This is why I decided in my trading program not to store the position of the decimal point, but use the minimum step size (increment size) as a parameter of each instrument.
I think in the class/data structure is necessary to add Instrument Tick Size variable/property and then dance from it. From tick size you could derive rounding function to fix precision for comparison. It's allow you to keep price data in double/decimal whatever you want.