问题
I would like to know how to format the data labels on a Pie Chart so it shows max 2 decimal characters, and never shows trailing zeros, for example:
2 -> 2
2.0 -> 2
2.566 -> 2.57
In other words, I am asking how to set dataLabelFormatString
parameter?
I know it is using sprintf
, thus I tried '%.2f' and '%g'. They do not solved my problem though. Since the first makes each number to show to decimal characters, the other just removes trailing zeros but doesn't work with precision as in this case the digits you place in front of it ,e.g. '%.2g' refer to the total length of the character.
I do not know how to, effectively, combine these two (is it even possible?). How to set the parameter, for example, to first format using '%.2f' then using '%g' and it should do the trick, but how to do it?
Can I maybe 'inject' an if/else into the format, if so then how?
Otherwise the only way I can think of would be to, once the plot is drawn, run a jquery script getting the labels and applying parseFloat(label.toFixed(2))
on each.
回答1:
To close this topic I am posting my answer here. I managed to solved this issue, thanks to jQuery
. Once again it appears to be a real life saver when it comes to doing the client side. :)
I have approached it similarly to my thought mentioned in my question, i.e. using parseFloat(label.toFixed(2))
. Though I did it in a slightly inverted way. I decided to set the chart to use label
for dataLabels
parameter. I use the $.jqplot.postDrawHooks.push(...)
to bind my function for execution once the chart is finished painting. My function modifies the legend labels to display names instead of percentage values which I calculate before I set them to data array.
This approach works perfectly as I would want it. To those interested, please find my jsfiddle showing the solution here.
If someone has a better solution I am very keen to move the accept from my answer at any time.
来源:https://stackoverflow.com/questions/10245521/jqplot-pie-chart-data-label-format-precision-without-trailing-zeros