79 lines
2.6 KiB
C++
79 lines
2.6 KiB
C++
#pragma once
|
|
#include "lib/utils/bts_assert.h"
|
|
#include "lib/utils/bts_array_size.h"
|
|
|
|
namespace bts {
|
|
namespace md {
|
|
|
|
static const double powers_10[] = {
|
|
1E-20, 1E-19, 1E-18, 1E-17, 1E-16, 1E-15, 1E-14, 1E-13, 1E-12, 1E-11, 1E-10, 1E-9, 1E-8, 1E-7, 1E-6, 1E-5, 1E-4, 1E-3, 1E-2, 1E-1,
|
|
1E0,
|
|
1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15, 1E16, 1E17, 1E18, 1E19, 1E20
|
|
};
|
|
static const int max_abs_power_10 = BTS_ARRAYSIZE(powers_10) / 2;
|
|
inline double pow10(int power) {
|
|
const int offset = power + max_abs_power_10;
|
|
const int powers_10_sz = BTS_ARRAYSIZE(powers_10);
|
|
bts_assert_d(offset >= 0 && offset < powers_10_sz);
|
|
if (offset >= 0 && offset < powers_10_sz) {
|
|
return powers_10[offset];
|
|
}
|
|
return std::numeric_limits<double>().quiet_NaN();
|
|
}
|
|
|
|
class IntPrice {
|
|
#ifdef _WIN32
|
|
int64_t _mantissa : 56;
|
|
int64_t _exponent : 8;
|
|
#else
|
|
int64_t _mantissa : 56;
|
|
int8_t _exponent : 8;
|
|
#endif
|
|
public:
|
|
IntPrice() : _mantissa(0), _exponent(127) {/*nan*/}
|
|
IntPrice(int64_t mantissa, int8_t exponent) : _mantissa(mantissa), _exponent(exponent) {}
|
|
IntPrice(const IntPrice& other) : _mantissa(other._mantissa), _exponent(other._exponent) {}
|
|
|
|
bool operator==(const IntPrice& other) const {
|
|
return _mantissa == other._mantissa && _exponent == other._exponent;
|
|
}
|
|
bool operator!=(const IntPrice& other) const {
|
|
return !(*this == other);
|
|
}
|
|
bool operator<(const IntPrice& other) const {
|
|
if (_exponent == other._exponent) {
|
|
return _mantissa < other._mantissa;
|
|
}
|
|
else {
|
|
return price() < other.price();
|
|
}
|
|
}
|
|
IntPrice operator - (const IntPrice& o) const {
|
|
//if(_exponent==o._exponent)
|
|
return IntPrice(_mantissa-o.mantissa(), _exponent);
|
|
}
|
|
int64_t mantissa() const { return _mantissa; }
|
|
int8_t exponent() const { return _exponent; }
|
|
double price() const {
|
|
if (is_nan()) return NO_PRICE;
|
|
return mantissa() * pow10(exponent());
|
|
}
|
|
bool is_nan() const { return _exponent == 127; }
|
|
};
|
|
static_assert(sizeof(IntPrice) == 8, "IntPrice should be this big |--------|");
|
|
extern IntPrice INT_NAN;
|
|
|
|
template <uint8_t PRECISION>
|
|
IntPrice IntPrice_from_double(double price) {
|
|
if (os::is_nan(price)) return INT_NAN;
|
|
double temp;
|
|
if (fabs(modf(price, &temp)) != 0.0) {
|
|
const double rounding = 0.5 * pow10(-PRECISION);
|
|
price += (price > 0) ? rounding : -rounding;
|
|
price *= pow10(PRECISION);
|
|
return {(int64_t)price, -PRECISION};
|
|
}
|
|
return {(int64_t)price, 0};
|
|
}
|
|
|
|
}} |