carto-react icon indicating copy to clipboard operation
carto-react copied to clipboard

Allow passing decimal precision as a prop for CategoryWidgetUI

Open azhars21 opened this issue 1 year ago • 4 comments

Description:

Currently, the CategoryWidgetUI component of react-ui package does not provide a way to set the decimal precision when displaying the "Other" category that contains the sum of all remaining categories. This can result in an issue where adding two numbers with decimal precision can lead to unexpected results due to the limitation of JavaScript's floating-point arithmetic.

Below is the screenshot of this issue: image

In order to avoid this issue, I would like to request an enhancement in the CategoryWidgetUI component that allows users to set the decimal precision for the "Other" category. This would enable users to ensure that the sum of all remaining categories is displayed accurately, without the need to manipulate the data beforehand.

Below is the code snippet which is causing this floating-point arithmetic issue: File: https://github.com/CartoDB/carto-react/blob/master/packages/react-ui/src/widgets/CategoryWidgetUI.js Snippet:

// Showing top or selected categories
        if (!blockedCategories.length) {
          const main = list.slice(0, maxItems);
          if (main.length < list.length) {
            const rest = list.slice(maxItems).reduce(
              (acum, elem) => {
                acum.value += elem.value;
                return acum;
              },
              { name: REST_CATEGORY, value: 0 }
            );
            return [...main, rest];
          } else {
            return main;
          }

Proposed Solution:

Ideally, this enhancement could be implemented by adding a new prop to the CategoryWidgetUI component, such as decimalPrecision, which would allow users to set the number of decimal places to display for the "Other" category. For example, if decimalPrecision is set to 2, the sum of the other categories will be rounded to two decimal places. If this is not feasible, I would appreciate any alternative solutions that can achieve the same goal.

Benefits:

This enhancement will provide greater control over the display of the sum of the other categories and prevent potential issues due to the limitation of JavaScript's floating-point arithmetic.

Thank you for your consideration.

azhars21 avatar Mar 01 '23 22:03 azhars21