Text reports show "-0.00" for negative values that round to zero, while the chart shows "0.00"
Bug description
Reports that send a chart as text format numbers on the server with superset/utils/number_format.py, which is meant to reproduce the frontend's d3-format output. For negative values that round to zero at the chosen precision, it keeps the minus sign, while d3-format (and so the chart in the browser) drops it.
>>> from superset.utils.number_format import format_number_with_config
>>> format_number_with_config(",.2f", None, -0.001)
'-0.00'
>>> format_number_with_config("(,.2f", None, -0.001)
'(0.00)'
>>> format_number_with_config("$,.2f", None, -0.004)
'-$0.00'
>>> format_number_with_config(",d", None, -0.4)
'-0'The same values rendered with d3-format 3.1.2 using Superset's locale (minus: "-"):
| format | value | d3-format (browser) | number_format.py (report) |
|---|---|---|---|
,.2f |
-0.001 | 0.00 |
-0.00 |
(,.2f |
-0.001 | 0.00 |
(0.00) |
$,.2f |
-0.004 | $0.00 |
-$0.00 |
.1% |
-0.0001 | 0.0% |
-0.0% |
,d |
-0.4 | 0 |
-0 |
,.2f |
-0.001 | 0.00 |
-0.00 |
+,.2f |
-0.001 | -0.00 |
-0.00 |
d3-format has an explicit rule for this in src/locale.js:
// If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;apply_sign in number_format.py decides the sign from the raw value (value < 0) and does not have this rule, so the emailed/Slack table can show -0.00 or (0.00) next to a chart that shows 0.00. Small negative values like this are common for things like differences or rounding noise from aggregations.
Expected behavior
The report text matches the chart: a negative value that formats to zero is shown without a sign (0.00, $0.00, 0), unless the + sign mode is used.
Actual behavior
The minus sign (or accounting parentheses) is kept: -0.00, (0.00), -$0.00, -0.
Suggested fix
In apply_sign, treat the value as non-negative when the formatted magnitude has no non-zero digit and the sign mode is not +, like d3 does.
Environment
- Superset version: master
- Python version: 3.11
Source: apache/superset