'ChartJS Datalabels plugin and negative numbers

Issue: I'm using the Datalabels plugin for Chartjs on a pie chart. It's working. Up until I feed it a negative number. The label only appears for positive numbers.

Live Sample: roi.fyi (pie chart, charts tab)

Details:

It would appear that only positive values are accessible by the formatter.

I'm using options.plugins.datalabels.formatter to append a label.

The function accepts two numbers: investment and profit.

I've narrowed the issue down to just the following:

formatter: function(value, context) {
    console.log(value);
}

If profit is positive, I see log entries for both numbers. Can be formatted fine.

If profit is negative, I see log entries for only the positive number.

Edit: not solved exactly but found a simple enough work-around (see below).



Solution 1:[1]

After beating my head against the table for a few hours it seems that this may just be the intended behavior of datalabels.

I managed to "solve" it pretty simply like this:

 profit = profit.replaceAll("-","");

The negative can be added back in later using the formatter. In my case, I use a different data object when profit is negative, color it red, and change the "profit" heading to "loss". Solved well enough!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1