import { useLayoutEffect, useState } from "react" function useNumber(num: number) { num = parseFloat(num.toFixed(2)) const [number, setNumber] = useState('0') /**数字转,字符串 */ function str(newNum: number) { let strNum = '' let count = 0 for (var i = JSON.stringify(newNum).length - 1; i >= 0; i--) { if (count % 3 == 0 && count != 0) { strNum = JSON.stringify(newNum).charAt(i) + "," + strNum; } else { strNum = JSON.stringify(newNum).charAt(i) + strNum; } count++ } return strNum } /**累加 */ useLayoutEffect(() => { let arr = JSON.stringify(num).split('.')//假如存在小数点分割,小数点后数字不处理累加,最后返回值时拼接上 num = parseInt(arr[0]) let newNum = 0 let strN: any = '1' let len = JSON.stringify(num).length let time: any = setInterval(() => { if (newNum < num) { Array(len).fill('').forEach((i: string, index: number) => { let n = JSON.stringify(num).slice((index + 1) * 1, len).length //从第2位开始取得末尾有几位数 let s = '1' strN = JSON.stringify(num).slice(0, (index + 1) * 1) Array(n).fill('').forEach((i: string) => { //计算获得每次累加多少数值 s += '0' strN += '0' }) if ((newNum + parseInt(s)) <= strN) { newNum += parseInt(s) let strNum = str(newNum) + (arr[1] ? `.${arr[1]}` : '') setNumber(strNum) } else if (JSON.stringify(num).slice(len - 1, len) !== JSON.stringify(newNum).slice(len - 1, len)) { newNum++ let strNum = str(newNum) + (arr[1] ? `.${arr[1]}` : '') setNumber(strNum) } }) } else { clearInterval(time) } }, 0) return () => { clearInterval(time) time = null } }, [num]) return <> {number === '0' ? 0 : {number}} } export default useNumber