I'm creating a donut chart that has 3 sections:
When the user hovers over each one of the colored sections it displays a percentage of 100%. Currently each section are as follows; green is 78%, yellow is 13%, and red is 8%. If you add all those together is does NOT equal 100%, it equals 99%
Each section has values which are whole numbers, coming from the end-point, and I'm trying to convert everything to percentages.
For this chart I have three values:
var values = [1397, 234, 149];
Those values need to equal 100% when added:
var sum = values.reduce((a, b) => a + b, 0); // this works great
To determine the percentage for each section I use:
var value = 0;
values.forEach(function(number) {
console.log(number + ' = ' + (number / sum) * 100);
result += (number / sum) * 100;
});
Which produces the following:
1397 = 78.48314606741573
234 = 13.146067415730336
149 = 8.370786516853933
result = 100
Now this is where I think the problem lies. I cannot display the floating point value because, well, it's not a percentage value. I decided to use Math.round()
to create whole numbers which I'm thinking is not the proper way.
How can I convert each one of the floating values to create percentages that equal to 100%? Is there an alternative to Math.round()
?