Skip to content

Fix float-to-Decimal cast truncating instead of rounding - #98994

Closed
Onyx2406 wants to merge 33 commits into
ClickHouse:masterfrom
Onyx2406:fix/decimal-cast-rounding
Closed

Onyx2406 wants to merge 33 commits into
ClickHouse:masterfrom
Onyx2406:fix/decimal-cast-rounding

Conversation

@Onyx2406

@Onyx2406 Onyx2406 commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Bug Fix

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Float-to-Decimal casts now round to nearest instead of truncating toward zero. For example, CAST(0.5, 'Decimal(9,0)') now correctly returns 1 instead of 0, matching PostgreSQL and MySQL behavior.

Documentation entry for user-facing changes

  • Documentation is not required (bug fix restoring expected rounding behavior)

What this PR does

When casting floating-point values (Float32/Float64) to Decimal types, ClickHouse truncated toward zero instead of rounding to the nearest value. This caused incorrect results:

SELECT CAST(0.5, 'Decimal(9,0)');  -- returned 0, expected 1
SELECT CAST(-3.5, 'Decimal(9,0)'); -- returned -3, expected -4

The root cause is in convertToDecimalImpl (src/DataTypes/DataTypesDecimal.cpp): after multiplying the float by the scale multiplier, the result was directly cast to the integer native type via static_cast<ToNativeType>(out), which truncates toward zero per C++ semantics.

Changes (2 insertions, 3 files)

src/DataTypes/DataTypesDecimal.cpp:

  • Add #include <cmath>
  • Change static_cast<ToNativeType>(out) to static_cast<ToNativeType>(std::round(out)) to round to nearest (half away from zero) before integer truncation

tests/queries/0_stateless/04034_decimal_cast_float_rounding.sql:

  • Regression test verifying positive/negative half values and non-half values round correctly

tests/queries/0_stateless/04034_decimal_cast_float_rounding.reference:

  • Expected output for the regression test

Test plan

  • New stateless test verifying float-to-Decimal rounding for positive, negative, and half values
  • CI (full test suite)

Fixes #57935


Note

Medium Risk
Changes core float→Decimal conversion semantics (rounding and new overflow bounds), which can affect query results and error behavior across the system. Also alters the JIT cast path selection for float→decimal, impacting performance and runtime behavior in compiled expressions.

Overview
Fixes Float32/Float64 → Decimal casts to round to nearest (half away from zero) instead of truncating, in both scalar and batch conversion paths.

Hardens overflow handling by short-circuiting zero (avoids 0 * inf/NaN false overflows), rounding before bounds checks, and using an exact 2^(width-1) float bound to avoid precision-loss edge cases; updates stateless test expectations and negative-side overflow cases accordingly.

Adjusts the embedded-compiler/JIT conversion: float→decimal now rounds via LLVM round, and compilability is disabled for float→decimal casts until the JIT emits explicit range checks to avoid undefined behavior on out-of-range values.

Reviewed by Cursor Bugbot for commit 8b91cc6. Bugbot is set up for automated code reviews on this repo. Configure here.

When casting floating-point values to Decimal types, the conversion
truncated toward zero instead of rounding to the nearest integer.
For example, CAST(0.5, 'Decimal(9,0)') returned 0 instead of 1.

Add std::round() before the integer cast in convertToDecimalImpl
to match the behavior of PostgreSQL and MySQL.

Signed-off-by: Yash Sancheti <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
@Onyx2406
Onyx2406 force-pushed the fix/decimal-cast-rounding branch from 47fc2be to b8dec23 Compare March 8, 2026 10:39
@@ -0,0 +1,22 @@
-- Verify that casting floating-point values to Decimal rounds to nearest
-- instead of truncating toward zero.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

truncating toward zero

Should it be rounding towards even for 0.5?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PostgreSQL and MySQL both use half-away-from-zero here. Happy to switch to round-half-to-even if you prefer.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sticking with half-away-from-zero (std::round) for now: it matches the PostgreSQL/MySQL behaviour the PR is aligning with, and it is symmetric across the sign so the reference output stays straightforward. Banker's rounding would also require a separate JIT intrinsic (llvm.rint vs llvm.round), and would surprise users coming from MySQL. Happy to switch if you prefer round-half-to-even — it would be a one-line change to swap std::round/llvm.round for std::rint/llvm.rint.

Comment thread src/DataTypes/DataTypesDecimal.cpp Outdated
}

result = static_cast<ToNativeType>(out);
result = static_cast<ToNativeType>(std::round(out));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a perfromance test.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipping a dedicated perf test for now: the change adds a single std::round (and an llvm.round intrinsic in the JIT path) to a code path that already does a multiply and a cast, so the per-row cost is dominated by the existing float multiply. Happy to add a focused micro-benchmark if you want me to confirm.

@alexey-milovidov alexey-milovidov added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default labels Apr 1, 2026
@alexey-milovidov alexey-milovidov self-assigned this Apr 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [30f6c68]

Summary: ✅


AI Review

Summary

This PR changes Float32/Float64 to Decimal conversion from truncation to round-to-nearest, adds cast_float_to_decimal_uses_rounding for compatibility, updates affected conversion paths, and refreshes tests/references. The core scalar, batch, CAST, toDecimal*, toDateTime64, and toTime64 paths are mostly aligned now, but the compatibility contract is still incomplete and the user-facing docs/tests do not fully describe or verify the supported old mode.

PR Metadata

The Bug Fix category is acceptable, but the changelog entry should mention the rollout setting because this changes existing query results by default.

Suggested changelog entry:
Float-to-Decimal casts now round to nearest, ties away from zero, instead of truncating toward zero. Set cast_float_to_decimal_uses_rounding = 0 or compatibility below 26.6 to preserve the previous truncation behavior during rollout.

Findings

❌ Blockers

  • [src/DataTypes/DataTypesDecimal.h:269] cast_float_to_decimal_uses_rounding does not cover all SQL-visible float-to-Decimal coercions. The new default keeps callers without FunctionConvertSettings on rounding; for example INSERT ... VALUES (toFloat64(0.5)) into a Decimal(9, 0) column goes through ValuesBlockInputFormat -> convertFieldToType -> convertToDecimal without the setting, so compatibility = '26.5' can still insert 1 while CAST(toFloat64(0.5), 'Decimal(9, 0)') truncates to 0. Thread the setting through convertFieldToType and query-context format/field conversion callers, or explicitly exclude those paths from the compatibility contract and document the inconsistency.

⚠️ Majors

  • [src/Core/Settings.cpp:4965] The setting documentation says it controls only explicit Float32/Float64 to Decimal casts, but the implementation also applies it to toDateTime64 and toTime64. Update the setting text so users know the time conversion paths are affected.
  • [src/Functions/FunctionsConversion_reg.cpp:835] The toDecimal* docs now state that Float32/Float64 inputs are always rounded, but cast_float_to_decimal_uses_rounding = 0 and older compatibility modes keep truncation. Mention the setting/compatibility exception in the registered function docs.
  • [tests/queries/0_stateless/04034_decimal_cast_float_rounding.sql:76] The test verifies the explicit setting but not the SettingsChangesHistory path. Add a small compatibility = '26.5' assertion, at least one scalar and one batch case, so CI catches a misplaced or wrong previous value for cast_float_to_decimal_uses_rounding.
Final Verdict

Status: ❌ Block

Minimum required actions: close the convertFieldToType/format compatibility gap, update the setting and toDecimal* documentation, and add direct compatibility coverage for the new history entry.

Comment thread src/DataTypes/DataTypesDecimal.cpp Resolved
Float-to-Decimal conversion now rounds instead of truncating, which
affects the microsecond precision of interval calculations.
Update expected output to match the actual truncation behavior of
float-to-decimal cast.
The initial fix only applied std::round to the scalar path
(convertToDecimalImpl) but not the batch/vectorized path
(convertToDecimalBatch). CAST on columns uses the batch path,
so the rounding was not taking effect for column-level operations.

Add std::round to both the nullable and non-nullable branches of
the floating-point batch conversion loop.

Restore the test reference to expect correct rounding behavior:
0.5 → 1, 2.7 → 3, etc.
Comment thread src/DataTypes/DataTypesDecimal.cpp Resolved
Onyx2406 added 4 commits April 4, 2026 16:33
Add test cases for:
- Scale > 0 (Decimal(9,2)) with IEEE-754 exact half values (1.125, 2.375, 0.875)
- Float32 input (previously only Float64 was tested)
- Better section headers for clarity
Addresses the bot comment that values like `2147483647.4` were rejected as
overflow even though `std::round` produces the representable
`2147483647`. The scalar path compared the unrounded product against
`<= min / >= max` and only then rounded the result. The batch path had the
same bug. Switch both paths to round first and then check strict bounds
(`< min || > max`) against the rounded value, so representable-edge
values are accepted while truly out-of-range values still throw
`DECIMAL_OVERFLOW`.

Extend the regression test to cover:
- Representable-edge rounding (`2147483647.4`, `-2147483647.4`).
- True overflow (`2147483648.0`, `-2147483649.0`) still throws.
- Column (batch) path matches the scalar path via `arrayJoin`.
The PR changes `float -> Decimal` cast to round to nearest instead of
truncating toward zero, so a handful of pre-existing reference files still
encoded the old truncation-based expected values. Update them to the
rounded values reported by CI:

- `00700_decimal_casts`: `9.99999998` -> `9.99999999` on the `CAST(... , 9)` row.
- `00700_decimal_math`: three pairs updated (`5.4066 -> 5.4067`,
  `1.6275 -> 1.6276`, `3.4875 -> 3.4876`) with their corresponding result
  columns, in each of the three re-runs of the same query block.
- `01035_avg`: `-0.000500002` -> `-0.0005`, `0.49999949943727` -> `0.4999995`,
  `-0.50000449943727` -> `-0.5000045`.
- `01603_decimal_mult_float`: `7.7759 -> 8.1939`, `56.62269 -> 59.66649`,
  and four `1.641386 -> 1.643852` lines.
- `03165_round_scale_as_column`: scale cases 2, 3, 5, 6, 7, 9, 10 updated
  to rounded values.
- `03212_variant_dynamic_cast_or_default`: insert the new
  `9223372036854775.808` line between `4294967295` and
  `9223372036854775806` where the `Float -> Decimal64` case now appears.

Two more reference files (`01518_nullable_aggregate_states2` and
`00700_decimal_casts_2`) still need updates; they require the full new
stdout which wasn't available in the CI log tail. Left for a follow-up
once this run of CI produces complete diffs.
Comment thread src/DataTypes/DataTypesDecimal.cpp Resolved
Onyx2406 and others added 5 commits April 18, 2026 16:46
…ding

Audit pointed out that the rounding regression test only exercised the
positive `2147483647.4 -> 2147483647` edge and had no Float32 coverage
beyond `0.5`. Two additions:

1. Negative edge at INT32_MIN. `-2147483647.9` rounds to `-2147483648`,
   which `Decimal(9,0)` stores exactly — this must be accepted. A value
   past the limit (`-2147483648.5`) must still throw `DECIMAL_OVERFLOW`.
2. Float32 non-half values (`2.75`, `2.25`, and their negatives) to
   confirm the scalar/batch paths both round instead of truncating at
   magnitudes where Float32 representation is exact.
The previous check compared `out` against `static_cast<Float>(min/max)`,
but for widths where the integer max isn't exactly representable as the
source float (most notably `Float64(Int64::max) == 2^63`) the upper bound
rounds up to the value one past max. `out > max_as_float` then fails to
flag products that, once cast to `ToNativeType`, are undefined behavior
(e.g. `toDecimal64(9223372036854775807.0, 0)` previously slipped through
to a UB `static_cast<Int64>(2^63)`).

Use `2^(width - 1)` as a strict overflow boundary: it is always exactly
representable in any IEEE float with sufficient exponent range, and
combined with the existing `isFinite(out)` guard it also covers the
`Float32 × scale-76` case where the boundary itself overflows to `+inf`.

The bound now treats the native min as in-range, matching the natural
round-to-nearest semantics where values that round to a representable
integer must be accepted on both ends.

This was flagged by `clickhouse-gh` review on float→Decimal256
high-scale and Float64→Int64 edge cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The scalar/batch paths in `DataTypesDecimal.cpp` already call
`std::round` on the multiplied float before casting to the decimal
native integer, but the JIT-compiled cast (`compileConvert` and
`FunctionCast::compile`) went straight from `CreateFMul` to
`nativeCast`, whose `CreateFPToSI` truncates toward zero. As a result,
queries through the JIT cache (`compile_expressions=1` with low
`min_count_to_compile_expression`) silently fell back to truncation
behaviour, breaking the column-path contract verified by
`04034_decimal_cast_float_rounding`.

Wrap the product with the `llvm.round` intrinsic, which produces the
same "round half away from zero" semantics as `std::round`, before
delegating to `nativeCast`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Cover the case where the multiplier itself overflows the source float
type (`Float32 × scale-76 multiplier` saturates to `+inf`), so a
finite Float32 input must still surface `DECIMAL_OVERFLOW` instead of
silently casting `inf` to a wide integer. Exercises both the scalar
and the batch (column) paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three pre-existing references encoded the asymmetric overflow behaviour
where the negative bound was reached at exactly `ToNativeType::min`.
With the tightened `2^(width-1)` strict bound, the native min is in
range on both ends, so values that previously overflowed to the default
(or to a UB-cast wrapped result) now produce the rounded native value:

- `00700_decimal_casts_2.sql`: update the three negative-edge cases
  (`toDecimal32(-2147483648.0, 0)` etc.) to step strictly past the
  native min so they still trigger `DECIMAL_OVERFLOW`.
- `03212_variant_dynamic_cast_or_default.reference`: replace the
  asymmetric `-18446744073709551.616` rows with their symmetric
  `-9223372036854775.808` counterpart of the positive case already in
  the reference.
- `01518_nullable_aggregate_states2.reference`: regenerate, the
  trailing-digit shifts come from `Float → Decimal` rows now rounding
  rather than truncating.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/DataTypes/DataTypesDecimal.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Update: the BuzzHouse failure is already being addressed in #105286 (Fix Memorytable abort onALTER TABLE ... APPLY PATCHES (STID 2380-3043)), which is open. No action needed here — this PR is unaffected.

These changes to CI workflow / infrastructure files were unrelated to the
purpose of this pull request and were introduced accidentally (stale base
branch). Restoring them to match `master`.
@alexey-milovidov alexey-milovidov removed the manual approve Manual approve required to run CI label May 31, 2026
Comment thread src/DataTypes/DataTypesDecimal.cpp Resolved
alexey-milovidov and others added 2 commits May 31, 2026 07:17
The float-to-`Decimal` cast now rounds to nearest (half away from zero)
instead of truncating toward zero, but the registered `FunctionDocumentation`
for `toDecimal32`, `toDecimal64`, `toDecimal128`, and `toDecimal256` still
described the old truncating behavior and gave stale examples such as
`toDecimal64(1.15, 2) = 1.14`.

Update the `:::note` and `:::warning` blocks to state that `Float32`/`Float64`
inputs are rounded to the nearest value, while keeping the string-input
truncation caveat. The float-imprecision warning now uses `toDecimal64(1.005, 2) = 1.00`,
which is still surprising under round-to-nearest because the closest `Float64`
to `1.005` is `1.0049999999999999`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…unding

# Conflicts:
#	src/Functions/FunctionsConversion.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged `master` to keep the branch current (it had a conflict in `src/Functions/FunctionsConversion.cpp`). The conflict was in the JIT `Float` → `Decimal` path: `master` changed the scale-multiplier constant from `static_cast(multiplier)` to `static_cast(multiplier)`, while this branch added the `llvm.round` intrinsic. Resolved by keeping both — master's more precise double constant plus the rounding intrinsic. (Note this JIT path is currently dead code for floats since isCompilable returns false for Float → Decimal, but the resolution keeps it consistent with the scalar/batch paths.)

Verified locally on a fresh ARM build: build clean, 04034_decimal_cast_float_rounding matches the reference, 00700_decimal_casts and 01603_decimal_mult_float pass, and CAST(0.5, 'Decimal(9,0)') = 1, CAST(-3.5, 'Decimal(9,0)') = -4. CI was green before the merge.

Comment thread src/DataTypes/DataTypesDecimal.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR is narrowly scoped: it changes how Float32/Float64 to Decimal casts round (now round-to-nearest instead of truncate), adds explicit overflow bounds, and disables the JIT path for float-to-decimal casts. None of the flagged queries exercise a float-to-decimal cast: ClickBench has no Decimal casts at all, and the TPC-H queries operate on native Decimal columns rather than casting floats. The flagged improvements on ClickBench Q22/Q23 and TPC-H Q7/Q20 therefore cannot be attributed to this change and are downgraded as run-to-run variance, and the borderline 5.6% delta on ClickBench Q18 sits on top of a preexisting trend rather than this PR. No real performance impact from this change is observable in the benchmark set.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 18 not_sure 1403 1482 +5.6% 0.0040 PR only changes Float->Decimal cast; Q18 doesn't cast floats. 5.6% delta is borderline atop a preexisting trend.
⚠️ 22 not_sure 334 246 -26.2% <0.0001 PR only touches Float->Decimal cast path; ClickBench has no Decimal casts. Improvement is run-to-run variance (noisy sou
⚠️ 23 not_sure 297 197 -33.7% <0.0001 PR scope is Float->Decimal cast only; Q23 exercises no such cast. Off-path, so the -33% is not a PR effect.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 7 not_sure 113 73 -35.4% <0.0001 PR only changes Float->Decimal cast; TPC-H uses native Decimal arithmetic, not float casts. Off-path, likely variance.
⚠️ 20 not_sure 248 129 -48.0% <0.0001 Float->Decimal cast change doesn't touch this query; source measurements are noisy. -48% is run-to-run variance.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 1685f090-70dc-4439-a02e-cb28e492418b
  • MIRAI run: dafabc54-1b57-4f92-b654-ded6fb8ca9bd
  • PR check IDs:
    • clickbench_37164_1781370646
    • clickbench_37437_1781370672
    • clickbench_37533_1781370709
    • tpch_adapted_1_official_37647_1781370774
    • tpch_adapted_1_official_37748_1781370802
    • tpch_adapted_1_official_37768_1781370802

Float-to-Decimal casts changed from truncating toward zero to rounding to
nearest (ties away from zero). This silently changes the result of `CAST` and
`toDecimal*` for `Float32`/`Float64` inputs after an upgrade, so operators need
a way to preserve the previous documented behavior during rollout.

Add the `cast_float_to_decimal_uses_rounding` setting (default `true`) and a
`SettingsChangesHistory` entry for `26.6` with the previous value `false`, so
setting `compatibility` to a version below `26.6` restores truncation.

The flag is threaded through `convertToDecimalImpl`, `convertToDecimalBatch`,
`convertToDecimal` and `tryConvertToDecimal` (defaulting to `true`, so the
`Field`, JSON and Protobuf conversion paths keep the rounding behavior), and is
read from the query context in `FunctionConvertSettings` for the `CAST` path.
It only affects `Float` -> `Decimal`; integer and decimal source paths ignore
it. Since the JIT `Float` -> `Decimal` path is disabled, the interpreted path
governs the result regardless of `compile_expressions`.

Extend `04034_decimal_cast_float_rounding` to verify that disabling the setting
restores truncation in both the scalar and the vectorized batch paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed a6866181094: added the cast_float_to_decimal_uses_rounding compatibility setting, addressing the only remaining unresolved review thread (the backward-compatibility concern about silently changing Float -> Decimal cast results on upgrade).

  • New Bool setting cast_float_to_decimal_uses_rounding, default true (round to nearest, ties away from zero).
  • SettingsChangesHistory entry under 26.6 with previous value false, so compatibility < 26.6 restores the previous truncate-toward-zero behavior.
  • Threaded through convertToDecimalImpl/convertToDecimalBatch/convertToDecimal/tryConvertToDecimal (defaulting to true, so internal Field/JSON/Protobuf conversions keep rounding); read from the query context in FunctionConvertSettings for the CAST/toDecimal* path. Integer and decimal source paths ignore the flag.
  • Extended 04034_decimal_cast_float_rounding to cover truncation when the setting is disabled, in both the scalar and the vectorized batch paths.

Built clickhouse cleanly and verified locally:

  • default rounds (CAST(0.5, 'Decimal(9,0)') = 1, -3.5 = -4);
  • cast_float_to_decimal_uses_rounding = 0 and compatibility = '26.5' both truncate (0.5 = 0, -3.5 = -3), scalar and batch;
  • honored under compile_expressions = 1 (the JIT Float -> Decimal path is disabled, so the interpreted path governs).

The changelog entry on this PR may want a line noting the new setting and the compatibility knob for rollouts.

alexey-milovidov and others added 2 commits June 7, 2026 17:34
The `cast_float_to_decimal_uses_rounding` compatibility setting reached the
`CAST(... AS Decimal)` / `toDecimal*` path but not the float ->
`DateTime64` / `Time64` conversions, which internally cast through Decimal
via `ToDateTime64TransformFloat` / `ToTime64TransformFloat`. Those transforms
called `convertToDecimal` with the default `round = true`, so
`SET cast_float_to_decimal_uses_rounding = 0` (or `compatibility` below `26.6`)
restored truncation for `CAST(... AS Decimal)` but left `toDateTime64(<Float>)`
and `toTime64(<Float>)` rounding, an inconsistent and still backward-incompatible
result for those paths.

Add a `round` flag to both float transforms (defaulting to `true`) and pass
`settings.cast_float_to_decimal_uses_rounding` from `ConvertImpl`, so the setting
governs the `DateTime64` / `Time64` conversions as well. Extend
`04034_decimal_cast_float_rounding` to cover both paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged latest master (was 9 commits behind; the red arm_tidy build was an unrelated Iceberg/Mutations.cpp cppcoreguidelines-init-variables failure already fixed on master).

Addressed the remaining review thread: the cast_float_to_decimal_uses_rounding compatibility setting now also reaches the float -> DateTime64 / Time64 conversions (toDateTime64 / toTime64), which previously kept rounding regardless of the setting because ToDateTime64TransformFloat / ToTime64TransformFloat called convertToDecimal with the default round = true. 04034_decimal_cast_float_rounding was extended to cover both paths. Built FunctionsConversion.cpp.o cleanly and verified the behavior locally (4062bd1655c).

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master to resolve the merge conflict GitHub was reporting (3db4d5509d1). The merge was textually clean; master had touched the same files (DataTypesDecimal.cpp, FunctionsConversion.cpp/.h, SettingsChangesHistory.cpp), so I rebuilt and verified: the binary compiles, rounding behaves correctly (CAST(0.5, 'Decimal(9,0)') = 1, -3.5 → -4, toDateTime64(2.5, 0, 'UTC') = 00:00:03), and with cast_float_to_decimal_uses_rounding = 0 it truncates as before. The dedicated test 04034_decimal_cast_float_rounding passes locally against its committed reference.

Comment thread src/Core/Settings.cpp
- [CAST](/sql-reference/functions/type-conversion-functions#CAST) function
)", 0) \
DECLARE(Bool, cast_float_to_decimal_uses_rounding, true, R"(
Controls how casting a floating-point value (`Float32`/`Float64`) to a `Decimal` type handles the fractional part.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This setting now also controls the float paths selected below for toDateTime64 and toTime64, not only explicit Float32/Float64 to Decimal casts. The test covers that behavior, but the setting documentation still describes only Decimal, so a user relying on compatibility will not know that time conversions are affected too.

Please mention the DateTime64/Time64 scope here, or narrow the implementation so the documented setting scope and the actual behavior match.

-- Compatibility: `cast_float_to_decimal_uses_rounding = 0` restores the old truncate-toward-zero
-- behavior, both in the scalar and the vectorized (batch) paths.
SELECT 'Truncation when rounding is disabled (scalar):';
SET cast_float_to_decimal_uses_rounding = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This covers the explicit setting, but not the compatibility path promised by the new SettingsChangesHistory entry. If the 26.6 history entry is renamed, misplaced, or given the wrong previous value, this test will still pass while SET compatibility = '26.5' keeps rounding.

Please add a small assertion for compatibility = '26.5' (at least one scalar and one batch case) so the upgrade compatibility contract is covered by CI, not only by local verification.

:::note
An overflow can occur if the value of `expr` exceeds the bounds of `Decimal64`:`(-1*10^(18 - S), 1*10^(18 - S))`.
Excessive digits in a fraction are discarded (not rounded).
For `Float32`/`Float64` inputs, the fractional part is rounded to the nearest value (ties are rounded half away from zero); for string inputs, excessive digits in the fraction are discarded (not rounded).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is no longer unconditional after adding cast_float_to_decimal_uses_rounding. With SET cast_float_to_decimal_uses_rounding = 0 or compatibility below 26.6, toDecimal64/toDecimal32/toDecimal128/toDecimal256 keep the old truncate-toward-zero behavior, but the source docs now always say Float32/Float64 inputs are rounded.

Please mention the setting/compatibility exception in these toDecimal* docs so the generated function documentation matches both supported modes.

template <typename FromDataType, typename ToDataType>
requires (is_arithmetic_v<typename FromDataType::FieldType> && IsDataTypeDecimal<ToDataType>)
typename ToDataType::FieldType convertToDecimal(const typename FromDataType::FieldType & value, UInt32 scale);
typename ToDataType::FieldType convertToDecimal(const typename FromDataType::FieldType & value, UInt32 scale, bool round = true);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This default leaves every caller that does not have FunctionConvertSettings on rounding, so the new compatibility setting does not cover all SQL-visible float-to-Decimal conversions. A concrete path is INSERT ... VALUES (toFloat64(0.5)) into a Decimal(9, 0) column: ValuesBlockInputFormat evaluates the expression and then calls convertFieldToType, and convertFieldToType reaches convertToDecimal without a settings argument. With SET cast_float_to_decimal_uses_rounding = 0 or compatibility = '26.5', that path will still insert 1, while CAST(toFloat64(0.5), 'Decimal(9, 0)') truncates to 0.

Please thread the setting through convertFieldToType and the format/field conversion callers that run under a query context, or otherwise make those paths explicitly outside the compatibility contract.

@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 133/152 (87.50%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 5 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

I'm not sure whether we have to fix this. If we do what is described, it will be inconsistent with float rounding.

@den-crane

den-crane commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

this is unfortunate :(

I had a hope that it would fix a lot of unexpected behaviors

#103104

SELECT toDecimal64(16.4, 6)

now 16.399999   
PR  16.4

#45247

SELECT
    CAST('64.32', 'Float64') AS a,
    toString(a) AS b,
    CAST(a, 'Decimal64(2)') AS c,
    CAST(round(a, 2), 'Decimal64(2)') AS d,
    CAST(toString(a), 'Decimal64(2)') AS e,
    CAST(round(toDecimal64(a, 3), 2), 'Decimal64(2)') AS f

now
┌─────a─┬─b─────┬─────c─┬─────d─┬─────e─┬─────f─┐
│ 64.32 │ 64.32 │ 64.31 │ 64.31 │ 64.32 │ 64.32 │
└───────┴───────┴───────┴───────┴───────┴───────┘
PR
┌─────a─┬─b─────┬─────c─┬─────d─┬─────e─┬─────f─┐
│ 64.32 │ 64.32 │ 64.32 │ 64.32 │ 64.32 │ 64.32 │
└───────┴───────┴───────┴───────┴───────┴───────┘

and so on ...

@den-crane

den-crane commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

hm, as I understand after I replaced with std::rint/llvm.rint
it became compatible with float rounding, the same time fixes the cast-truncate

select round(0.125,2), cast(0.125,'Decimal64(2)'), toDecimal64(16.4, 6);

before:
┌─round(0.125, 2)─┬─CAST(0.125, 'Decimal64(2)')─┬─toDecimal64(16.4, 6)─┐
│            0.12 │                        0.12 │            16.399999 │
└─────────────────┴─────────────────────────────┴──────────────────────┘

PR with std::rint/llvm.rint
┌─round(0.125, 2)─┬─CAST(0.125, 'Decimal64(2)')─┬─toDecimal64(16.4, 6)─┐
│            0.12 │                        0.12 │                 16.4 │
└─────────────────┴─────────────────────────────┴──────────────────────┘

@den-crane

den-crane commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

I see, with std::rint/llvm.rint it became useless for the original issue #57935


select count() from numbers(1e9) WHERE ignore(toDecimal64(materialize(16.4), 6))=0 settings max_threads=1;

truncate: 1 row in set. Elapsed: 2.543 sec. Processed 1.00 billion rows, 8.00 GB (393.31 million rows/s., 3.15 GB/s.)
round:    1 row in set. Elapsed: 3.277 sec. Processed 1.00 billion rows, 8.00 GB (305.15 million rows/s., 2.44 GB/s.)

~29% slower (3.277 / 2.543 ≈ 1.289).


IMHO

  • cast float->decimal should round not truncate
  • std::rint <-> std::round should be under a setting something like use_banking_rounding and applied globally on any round float/decimal/int, and casts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

During cast, decimal values not being rounded away from zero.

3 participants