|
1 | 1 | import { animate, motion, useMotionValue, useTransform } from "framer-motion"; |
2 | | -import { useEffect } from "react"; |
| 2 | +import { useEffect, useMemo } from "react"; |
3 | 3 |
|
4 | | -export function AnimatedNumber({ value, duration = 0.5 }: { value: number; duration?: number }) { |
| 4 | +/** |
| 5 | + * Determines the number of decimal places to display based on the value. |
| 6 | + * - For integers or large numbers (>=100), no decimals |
| 7 | + * - For numbers >= 10, 1 decimal place |
| 8 | + * - For numbers >= 1, 2 decimal places |
| 9 | + * - For smaller numbers, up to 4 decimal places |
| 10 | + */ |
| 11 | +function getDecimalPlaces(value: number): number { |
| 12 | + if (Number.isInteger(value)) return 0; |
| 13 | + |
| 14 | + const absValue = Math.abs(value); |
| 15 | + if (absValue >= 100) return 0; |
| 16 | + if (absValue >= 10) return 1; |
| 17 | + if (absValue >= 1) return 2; |
| 18 | + if (absValue >= 0.1) return 3; |
| 19 | + return 4; |
| 20 | +} |
| 21 | + |
| 22 | +export function AnimatedNumber({ |
| 23 | + value, |
| 24 | + duration = 0.5, |
| 25 | + decimalPlaces, |
| 26 | +}: { |
| 27 | + value: number; |
| 28 | + duration?: number; |
| 29 | + /** Number of decimal places to display. If not provided, auto-detects based on value. */ |
| 30 | + decimalPlaces?: number; |
| 31 | +}) { |
5 | 32 | const motionValue = useMotionValue(value); |
6 | | - let display = useTransform(motionValue, (current) => Math.round(current).toLocaleString()); |
| 33 | + |
| 34 | + // Determine decimal places - use provided value or auto-detect |
| 35 | + const decimals = useMemo( |
| 36 | + () => (decimalPlaces !== undefined ? decimalPlaces : getDecimalPlaces(value)), |
| 37 | + [decimalPlaces, value] |
| 38 | + ); |
| 39 | + |
| 40 | + const display = useTransform(motionValue, (current) => { |
| 41 | + if (decimals === 0) { |
| 42 | + return Math.round(current).toLocaleString(); |
| 43 | + } |
| 44 | + return current.toLocaleString(undefined, { |
| 45 | + minimumFractionDigits: decimals, |
| 46 | + maximumFractionDigits: decimals, |
| 47 | + }); |
| 48 | + }); |
7 | 49 |
|
8 | 50 | useEffect(() => { |
9 | 51 | animate(motionValue, value, { |
|
0 commit comments