1

When using react-spring to animate-up a number from 0 to x, is it possible to display that number with commas as "thousand separators" (as described here)?

The goal is to display this number as "123,456" - while still animating it up nicely!

const x = 123456; 

Basic react-spring number animation:

<Spring
    from={{
        number: 0,
    }}
    to={{
        number: x,
    }}
    config={{
        duration: 500
    }}
>
    {props => (
        <div>
            {props.number?.toFixed()}
        </div>
    )}
</Spring>
Ben
  • 15,938
  • 19
  • 92
  • 138

2 Answers2

1

Use this:

{new Intl.NumberFormat().format(Math.round(props.number)}

The NumberFormat() from the Intl API will provide the commas for you where they belong.

Reference

Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
  • Oh, right, looks like I was overthinking this. You're correct, I can simply format the output react-spring generates (without having to worry about how it does it). However, your answer should be `{new Intl.NumberFormat().format(props.number?.toFixed())}` to ensure there aren't any decimal points in the result (as per the question's code example). – Ben Feb 05 '21 at 13:46
  • Do you know what browser support is like for NumberFormat() from the Intl API? – Ben Feb 05 '21 at 13:51
  • [Browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat#browser_compatibility) – Randy Casburn Feb 05 '21 at 20:49
0

You can convert a number to a string with some formatting using Number.prototype.toLocaleString(). Format the value before outputting it with the specified locale.

The example below uses the EN-us locale which will use comma's to separate thousands and a dot to indicate decimals.

Or you can omit the value and it will detect the locale of the user.

const output = document.getElementById('output');
let count = 10000;

setInterval(() => {
  output.value = count.toLocaleString('EN-us');
  count += 10000;
}, 50);
<output id="output"></output>
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32