带有千位分隔符的动画数字

问题描述 投票:0回答:3

当使用react-spring动画从0到x的数字时,是否可以用逗号将该数字显示为“千位分隔符”(如此处所述)?

目标是将这个数字显示为“123,456” - 同时仍然很好地动画化它!

const x = 123456; 

基本的react-spring数字动画:

<Spring
    from={{
        number: 0,
    }}
    to={{
        number: x,
    }}
    config={{
        duration: 500
    }}
>
    {props => (
        <div>
            {props.number?.toFixed()}
        </div>
    )}
</Spring>
javascript reactjs numbers react-spring
3个回答
1
投票

使用这个:

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

Intl API 中的 NumberFormat() 将为您提供逗号所属的位置。

参考


0
投票

您可以使用

Number.prototype.toLocaleString()
将数字转换为具有某种格式的字符串。在使用指定的区域设置输出之前格式化该值。

下面的示例使用

EN-us
区域设置,该区域设置将使用逗号分隔千位并使用点表示小数。

或者您可以省略该值,它将检测用户的区域设置。

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

setInterval(() => {
  output.value = count.toLocaleString('EN-us');
  count += 10000;
}, 50);
<output id="output"></output>


0
投票

您可以使用react-spring的

useSpring
钩子和
animated
组件来创建一个对数字进行动画处理的React组件。

如果您随后将

.toFixed(0)
值包装为
Number
并调用
.toLocaleString("en-US")
,它将添加适当的逗号。

从 n 开始计数并使用逗号的组件示例。


import { useSpring, animated } from "react-spring";

interface AnimatedNumberProps {
  n: number;
}

/**
 * Component that animates from 0 to n
 */
export default function AnimatedNumber(props: AnimatedNumberProps) {
  const { n } = props;

  const { number } = useSpring({ number: n, from: { number: 0 } });

  return (
    <animated.div>
      {number.to((n) => Number(n.toFixed(0)).toLocaleString("en-US"))}
    </animated.div>
  );
}

© www.soinside.com 2019 - 2024. All rights reserved.