Report
to_char() on float4/float8 with the V format doesn't check the 10^n scale for overflow, so it returns literal "Infinity"/"NaN"; SG/PL patterns after the decimal point are silently dropped, losing the sign
- Severity
- 15
- Blamed commit
- b866d2e2d79416f8497e4dffa7e800298d018f6c
On 27 branches
REL7_1_STABLE, REL7_2_STABLE, REL7_3_STABLE, REL7_4_STABLE, REL8_0_STABLE, REL8_1_STABLE, REL8_2_STABLE, REL8_3_STABLE, REL8_4_STABLE, REL9_0_STABLE, REL9_1_STABLE, REL9_2_STABLE, REL9_3_STABLE, REL9_4_STABLE, REL9_5_STABLE, REL9_6_STABLE, REL_10_STABLE, REL_11_STABLE, REL_12_STABLE, REL_13_STABLE, REL_14_STABLE, REL_15_STABLE, REL_16_STABLE, REL_17_STABLE, REL_18_STABLE, REL_19_STABLE, master
Summary
Reported on pgsql-bugs as BUG #19810 against 18.6.
The float4/float8 to_char() paths compute the V (shift by 10^n) multiplier as a double with pow() and no overflow guard, unlike the int4/int8/numeric paths. Representable results therefore print as literal "Infinity" or "NaN" text, and whether overflow shows as "#####" or "Infinity" depends on the format width.
Separately, SG and PL patterns placed after the decimal point are dropped, together with any following literal text, so negative values print without a sign.
Reproduction
SELECT to_char(1e-300::float8, 'FM9V' || repeat('9', 309));
-- Infinity, expected 1000000000
SELECT to_char(0::float8, 'FM9V' || repeat('9', 309));
-- NaN
SELECT to_char(1e308::float8, 'FM9V9999999');
-- Infinity, while 'FM9V999999' gives #######
SELECT to_char('-100'::numeric, 'FM999.SG');
-- '100' (sign lost)
SELECT to_char('123.4'::numeric, 'FM999.PL');
-- '123'
Analysis
float4_to_char() and float8_to_char() in formatting.c do:
double multi = pow((double) 10, (double) Num.multi);
val = value * multi;
with no check that multi or the product is finite. For 309 V digits, pow() overflows to Infinity, so 1e-300 * Inf prints "Infinity" and 0 * Inf prints "NaN". The int4/int8 paths scale with checked integer or numeric arithmetic instead.
The blame points at the commit that added the V multiplier to the float paths. The SG/PL-after-decimal-point loss is a separate defect in the same function family whose origin was not identified.
Notes
A patch for the V-scaling part only was posted in the thread (0001-Fix-float-to_char-V-scaling.patch, reply CAB8bMiu+KeLVhNx0TWnj5O41FLgBZFb+fP5gmkJDV7gj-ZqTKw@mail.gmail.com). No fix commit was found.
Branches: the float V-scaling code is unchanged on REL_14 through master. Not reproduced by the Annex bots; the reproduction above is from the pgsql-bugs report.