Formatting an interpolated string or number in d3

I use d3 to animate text to show the user's progress in completing a task. For example, if they completed 32.51% of the task, the text will animate from 0% to 32.51% in 2 seconds or so.

To do this, I use the d3 attrTween method for the svg text element in combination with d3.interpolate. Interpolation works fine, but I have a little problem with text formatting. I would like 4 digits to always be displayed in the text, therefore 0% = 00.00%, 4.31% = 04.31%, etc. It would be nice to be able to do this without having to publish what the interpolator returns. In other words, without having to accept the return percentage and check if there are 4 digits and add a zero pad on both sides before placing it in the DOM.

As a test, I tried to specify the format I would like by setting the a and b values ​​for the interpolator in this way to d3.interpolate("00.00", "30.00") , but the final text is "30" when trailing zeros are cut off.

Any suggestions?

+4
source share
1 answer

You can add a custom interpolator to d3.interpolators - see the docs . The example given in the documents is very close to yours - the only real change indicates the output format, which in your case should be:

 d3.format('05.2f'); // 0-padding, string width 5, 2 decimal places 

Paste this into your doc example (note that I also changed the regex accordingly and added a percent sign):

 d3.interpolators.push(function(a, b) { var re = /^(\d\d\.\d\d)%$/, ma, mb, f = d3.format('05.2f'); if ((ma = re.exec(a)) && (mb = re.exec(b))) { a = parseFloat(ma[1]); b = parseFloat(mb[1]) - a; return function(t) { return f(a + b * t) + '%'; }; } }); d3.interpolate("00.00%", "30.00%")(1/5); // "06.00%" d3.interpolate("00.00%", "30.00%")(1/3); // "10.00%" 
+6
source

Source: https://habr.com/ru/post/1436178/


All Articles