1
0
mirror of https://github.com/postgres/postgres.git synced 2025-09-03 15:22:11 +03:00

Fix division-by-zero error in to_char() with 'EEEE' format.

This fixes a long-standing bug when using to_char() to format a
numeric value in scientific notation -- if the value's exponent is
less than -NUMERIC_MAX_DISPLAY_SCALE-1 (-1001), it produced a
division-by-zero error.

The reason for this error was that get_str_from_var_sci() divides its
input by 10^exp, which it produced using power_var_int(). However, the
underflow test in power_var_int() causes it to return zero if the
result scale is too small. That's not a problem for power_var_int()'s
only other caller, power_var(), since that limits the rscale to 1000,
but in get_str_from_var_sci() the exponent can be much smaller,
requiring a much larger rscale. Fix by introducing a new function to
compute 10^exp directly, with no rscale limit. This also allows 10^exp
to be computed more efficiently, without any numeric multiplication,
division or rounding.

Discussion: https://postgr.es/m/CAEZATCWhojfH4whaqgUKBe8D5jNHB8ytzemL-PnRx+KCTyMXmg@mail.gmail.com
This commit is contained in:
Dean Rasheed
2021-08-05 09:27:35 +01:00
parent fa604e0dd0
commit ecbdbdfd90
3 changed files with 76 additions and 29 deletions

View File

@@ -1794,6 +1794,38 @@ FROM v;
NaN | #.####### | #.####### | #.#######
(7 rows)
WITH v(exp) AS
(VALUES(-16379),(-16378),(-1234),(-789),(-45),(-5),(-4),(-3),(-2),(-1),(0),
(1),(2),(3),(4),(5),(38),(275),(2345),(45678),(131070),(131071))
SELECT exp,
to_char(('1.2345e'||exp)::numeric, '9.999EEEE') as numeric
FROM v;
exp | numeric
--------+----------------
-16379 | 1.235e-16379
-16378 | 1.235e-16378
-1234 | 1.235e-1234
-789 | 1.235e-789
-45 | 1.235e-45
-5 | 1.235e-05
-4 | 1.235e-04
-3 | 1.235e-03
-2 | 1.235e-02
-1 | 1.235e-01
0 | 1.235e+00
1 | 1.235e+01
2 | 1.235e+02
3 | 1.235e+03
4 | 1.235e+04
5 | 1.235e+05
38 | 1.235e+38
275 | 1.235e+275
2345 | 1.235e+2345
45678 | 1.235e+45678
131070 | 1.235e+131070
131071 | 1.235e+131071
(22 rows)
WITH v(val) AS
(VALUES('0'::numeric),('-4.2'),('4.2e9'),('1.2e-5'),('inf'),('-inf'),('nan'))
SELECT val,

View File

@@ -939,6 +939,13 @@ SELECT val,
to_char(val::float4, '9.999EEEE') as float4
FROM v;
WITH v(exp) AS
(VALUES(-16379),(-16378),(-1234),(-789),(-45),(-5),(-4),(-3),(-2),(-1),(0),
(1),(2),(3),(4),(5),(38),(275),(2345),(45678),(131070),(131071))
SELECT exp,
to_char(('1.2345e'||exp)::numeric, '9.999EEEE') as numeric
FROM v;
WITH v(val) AS
(VALUES('0'::numeric),('-4.2'),('4.2e9'),('1.2e-5'),('inf'),('-inf'),('nan'))
SELECT val,