0

I want to do a counter transition effect in D3 similar to this: http://jsfiddle.net/c5YVX/8/

Would it be possible to achieve the same effect using a value formatted as currency (applying a format)? If so, how?

var start_val = 0,
duration = 5000,
end_val = [0.06, 14, 1.33333, -232332312.00, 99999];

var qSVG = d3.select("body").append("svg").attr("width", 200).attr("height", 200);

qSVG.selectAll(".txt")
    .data(end_val)
    .enter()
    .append("text")
    .text(start_val)
    .attr("class", "txt")
    .attr("x", 10)
    .attr("y", function(d, i) {
       return 50 + i * 30
    })
.transition()
.duration(3000)
    .tween("text", function(d) {
        var i = d3.interpolate(this.textContent, d),
            prec = (d + "").split("."),
            round = (prec.length > 1) ? Math.pow(10, prec[1].length) : 1;

        return function(t) {
            this.textContent = Math.round(i(t) * round) / round;
        };
    });
Gilbert
  • 15
  • 1
  • 4

2 Answers2

1
return function(t) {
    this.textContent = '$' + (Math.round(i(t) * round) / round).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

The regex for commas is taken from here.

Community
  • 1
  • 1
Rasmus Elm
  • 51
  • 7
0

I may be too late for the party, But this worked for me like charm.

.tween('text', function() {
                //Reformat the textContent to a integer value;

                var content = this.textContent == '' ? 0 : parseInt(this.textContent.replace('$', '').replace(',', ''));
                var i = d3.interpolate(content, d.ccCount);
                return function(t) {
                  this.textContent = '$' + d3.format(",")(Math.round(i(t)));
                };
              });
sam
  • 2,426
  • 2
  • 20
  • 29