Capítulo 168 de 411

Chapter 168: Format Number With Commas (Helper)

Core Idea

A small helper that formats a raw number into a comma-grouped string with a fixed number of decimal places (e.g. 1000.254145"1,000.25"), handy for animating counters.

Key Concepts

  • Uses toLocaleString("en-US") for comma grouping, then manually pads/truncates the decimal portion to the requested length.
  • Pairs naturally with a tween's onUpdate to render a live-updating formatted counter.

Code Examples

function formatNumber(value, decimals) {
  let s = (+value).toLocaleString("en-US").split(".");
  return decimals ? s[0] + "." + ((s[1] || "") + "00000000").substr(0, decimals) : s[0];
}

let obj = { num: 100 };
gsap.to(obj, {
  num: 10500,
  onUpdate: () => (myElement.innerText = "$" + formatNumber(obj.num, 2)),
});
  • What it demonstrates: tweening a plain object property and rendering it into the DOM as a formatted string every frame via onUpdate.

Key Takeaways

  1. GSAP can tween any numeric object property, not just CSS/DOM values — this is the standard pattern for animated counters.

Connects To

  • onUpdate callback (GSAP core): the mechanism this helper is designed to be used inside.