ClickHouse/clickhouse-cpp

how to get float value from ColumnDecimal?

druidfund opened this issue · 1 comments

the output is not expected, is there something wrong with following code?

client->Execute("CREATE TEMPORARY TABLE IF NOT EXISTS test_decimal (d Decimal(18,4))");
	auto d = std::make_shared<clickhouse::ColumnDecimal>(18, 4);
	clickhouse::Block b;
    d->Append("21.12");
    b.AppendColumn("d", d);
    client->Insert("test_decimal", b);

	client->Select("SELECT d FROM test_decimal", [](const clickhouse::Block& block)
        {
            for (size_t c = 0; c < block.GetRowCount(); ++c) {
                auto col = block[0]->As<clickhouse::ColumnDecimal>();
                std::cout << (float)col->At(c) << std::endl;
            }
        }
    );

the output is: 211200
expected output is: 21.12

Enmk commented

You have to consider how decimal stores data and what the values actually are. Basically decimal value is
D = WholePart * 10^precision + FractionalPart. E.g. for type Decimal(6) value of 1.234 is stored as 1234000.

So in order to get floating-point value from that representation, you have to divide int-value by 10^precision:

const ColumnDecimal * c = ///...
const auto divider = std::pow(10, c->GetPrecision());
/// ...
c->At(i) / divider;