useNumber.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { useLayoutEffect, useState } from "react"
  2. function useNumber(num: number) {
  3. num = parseFloat(num.toFixed(2))
  4. const [number, setNumber] = useState<string>('0')
  5. /**数字转,字符串 */
  6. function str(newNum: number) {
  7. let strNum = ''
  8. let count = 0
  9. for (var i = JSON.stringify(newNum).length - 1; i >= 0; i--) {
  10. if (count % 3 == 0 && count != 0) {
  11. strNum = JSON.stringify(newNum).charAt(i) + "," + strNum;
  12. } else {
  13. strNum = JSON.stringify(newNum).charAt(i) + strNum;
  14. }
  15. count++
  16. }
  17. return strNum
  18. }
  19. /**累加 */
  20. useLayoutEffect(() => {
  21. let arr = JSON.stringify(num).split('.')//假如存在小数点分割,小数点后数字不处理累加,最后返回值时拼接上
  22. num = parseInt(arr[0])
  23. let newNum = 0
  24. let strN: any = '1'
  25. let len = JSON.stringify(num).length
  26. let time: any = setInterval(() => {
  27. if (newNum < num) {
  28. Array(len).fill('').forEach((i: string, index: number) => {
  29. let n = JSON.stringify(num).slice((index + 1) * 1, len).length //从第2位开始取得末尾有几位数
  30. let s = '1'
  31. strN = JSON.stringify(num).slice(0, (index + 1) * 1)
  32. Array(n).fill('').forEach((i: string) => { //计算获得每次累加多少数值
  33. s += '0'
  34. strN += '0'
  35. })
  36. if ((newNum + parseInt(s)) <= strN) {
  37. newNum += parseInt(s)
  38. let strNum = str(newNum) + (arr[1] ? `.${arr[1]}` : '')
  39. setNumber(strNum)
  40. } else if (JSON.stringify(num).slice(len - 1, len) !== JSON.stringify(newNum).slice(len - 1, len)) {
  41. newNum++
  42. let strNum = str(newNum) + (arr[1] ? `.${arr[1]}` : '')
  43. setNumber(strNum)
  44. }
  45. })
  46. } else {
  47. clearInterval(time)
  48. }
  49. }, 0)
  50. return () => {
  51. clearInterval(time)
  52. time = null
  53. }
  54. }, [num])
  55. return <>
  56. {number === '0' ? <span>0</span> : <span>{number}</span>}
  57. </>
  58. }
  59. export default useNumber