Skip to content

to_wei decimal precision issue #15

Description

@KonstantinUtkin

Greetings!

Having some tests using Microsoft Visual Studio 2026 and corresponding compiler (v.19.51.36243), noticed that fractional rounding is not working as expected (later reproduced it with GCC 11.5.0 20240719). Unfortunalely, Polymarkets is too strict in terms of precision (instead of threating it like "this price or better"), so it's causing orders rejection.

Example to reproduce is the following:

auto v2 = 3.0 / (1.0 - 0.01);
auto output = polymarket::to_wei(v2, 6, true);

This prints "3030303".

We may apply "rounding" trick to reach 2-digit precision (as Polymarket needs):

double __roundDouble(double input) {
    unsigned int dig = 100;
    auto a = input * dig;
    auto b = std::round(a);
    auto c = b / dig;
    return c;
}

It gives 3.0299999999999998. If we pass it to "to_wei", we get "3029999" instead of expected "3030000".

I would suggest to stringify it to the "wei" in the following manner:

(assuming dig_round = 2 and dig_result = 6 for Polymarkets)

std::string to_wei2(double val, unsigned int dig_round, unsigned int dig_result) {
    auto mult = __getMultiplierForDigits(dig_round);
    auto tmp = val * mult;
    tmp = std::round(tmp);
    long long cut = static_cast<long long>(tmp);
    auto rounded = std::to_string(cut);
    int pad_zeroes = dig_result - dig_round;
    while (pad_zeroes > 0) {
        rounded.append("0");
        pad_zeroes--;
    }
    return rounded;
}

It's not a good solution also, because it's not covering all range of "double", more like a crutch to fit values we may meet submitting orders to polymarkets, and assuming that dig_round < dig_result. It might be better to modify existing to_wei to achieve the same goal (despite it's using string streams which are relatively "heavy").

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions