Skip to content

Commit

Permalink
Fix issue with leading decimal places
Browse files Browse the repository at this point in the history
  • Loading branch information
WillAyd committed Sep 26, 2024
1 parent 4edc45e commit a1cf141
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/pantab/writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -360,9 +360,21 @@ class DecimalInsertHelper : public InsertHelper {
std::string str{reinterpret_cast<const char *>(buffer.data),
static_cast<size_t>(buffer.size_bytes)};
// The Hyper API wants the string to include the decimal place, which
// nanoarrow does not provide
if (scale_ > 0)
str = str.insert(str.size() - scale_, 1, '.');
// nanoarrow does not provide.
if (scale_ > 0) {
// nanoarrow strips leading zeros
const auto insert_pos = static_cast<int64_t>(str.size()) - scale_;
if (insert_pos < 0) {
std::string newstr{};
newstr.reserve(str.size() - insert_pos + 1);
newstr.append(1, '.');
newstr.append(-insert_pos, '0');
newstr.append(str, str.size());
str = std::move(newstr);
} else {
str = str.insert(str.size() - scale_, 1, '.');
}
}

constexpr auto PrecisionLimit = 39; // of-by-one error in solution?
if (precision_ >= PrecisionLimit) {
Expand Down
17 changes: 17 additions & 0 deletions tests/test_writer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
import decimal
import re

import narwhals as nw
Expand Down Expand Up @@ -395,3 +396,19 @@ def test_writer_invalid_process_params_raises(tmp_hyper):
msg = r"No internal setting named 'not_a_real_parameter'"
with pytest.raises(RuntimeError, match=msg):
pt.frame_to_hyper(frame, tmp_hyper, table="test", process_params=params)


@pytest.mark.parametrize(
"value,precision,scale",
[
("0.00", 3, 2),
("0E-10", 3, 2),
("100", 3, 0),
("1.00", 3, 2),
(".001", 3, 3),
],
)
def test_write_decimal_values(tmp_hyper, value, precision, scale):
arr = pa.array([decimal.Decimal(value)], type=pa.decimal128(precision, scale))
tbl = pa.Table.from_arrays([arr], names=["col"])
pt.frame_to_hyper(tbl, tmp_hyper, table="test")

0 comments on commit a1cf141

Please sign in to comment.