The way I'm doing it right now is:
#include <iostream>
#include <iomanip>
#include <cmath>
int main() {
double price = 6.35;
double tick_size = 0.01;
// Suppose we have to round up
double rounded = std::ceil(price / tick_size) * tick_size;
std::cout << std::setprecision(20) << "original = " << price
<< " | rounded = " << rounded << std::endl;
}
Output is:
original = 6.3499999999999996447 | rounded = 6.3500000000000005329
There lies the problem. The actual representation of 6.35
in double is 6.3499999999999996447
. But when I round using tick_size
I get something else.
My goal is to get exact double representations of those multiples of tick_size
. How do I achieve this?