Repository navigation
Conversation
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]>
47fc2be to
b8dec23
Compare
| @@ -0,0 +1,22 @@ | |||
| -- Verify that casting floating-point values to Decimal rounds to nearest | |||
| -- instead of truncating toward zero. | |||
There was a problem hiding this comment.
truncating toward zero
Should it be rounding towards even for 0.5?
There was a problem hiding this comment.
PostgreSQL and MySQL both use half-away-from-zero here. Happy to switch to round-half-to-even if you prefer.
There was a problem hiding this comment.
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.
| } | ||
|
|
||
| result = static_cast<ToNativeType>(out); | ||
| result = static_cast<ToNativeType>(std::round(out)); |
There was a problem hiding this comment.
Needs a perfromance test.
There was a problem hiding this comment.
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.
|
Workflow [PR], commit [30f6c68] Summary: ✅
AI ReviewSummaryThis PR changes PR MetadataThe Suggested changelog entry: Findings❌ Blockers
Final VerdictStatus: ❌ Block Minimum required actions: close the |
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.
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.
…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]>
|
Update: the |
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`.
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
|
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 — Verified locally on a fresh ARM build: build clean, |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (3 of 43)
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_officialFlagged queries (2 of 22)
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
|
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]>
|
Pushed
Built
The changelog entry on this PR may want a line noting the new setting and the |
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]>
|
Merged latest Addressed the remaining review thread: the |
|
Merged |
| - [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. |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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). |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
LLVM Coverage Report
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 |
|
I'm not sure whether we have to fix this. If we do what is described, it will be inconsistent with float rounding. |
|
this is unfortunate :( I had a hope that it would fix a lot of unexpected behaviors and so on ... |
|
hm, as I understand after I replaced with |
|
I see, with ~29% slower (3.277 / 2.543 ≈ 1.289). IMHO
|
Changelog category (leave one):
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 returns1instead of0, matching PostgreSQL and MySQL behavior.Documentation entry for user-facing changes
What this PR does
When casting floating-point values (
Float32/Float64) toDecimaltypes, ClickHouse truncated toward zero instead of rounding to the nearest value. This caused incorrect results: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 viastatic_cast<ToNativeType>(out), which truncates toward zero per C++ semantics.Changes (2 insertions, 3 files)
src/DataTypes/DataTypesDecimal.cpp:#include <cmath>static_cast<ToNativeType>(out)tostatic_cast<ToNativeType>(std::round(out))to round to nearest (half away from zero) before integer truncationtests/queries/0_stateless/04034_decimal_cast_float_rounding.sql:tests/queries/0_stateless/04034_decimal_cast_float_rounding.reference:Test plan
Fixes #57935
Note
Medium Risk
Changes core float→
Decimalconversion 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→Decimalcasts 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/NaNfalse overflows), rounding before bounds checks, and using an exact2^(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.