Skip to content

Commit 141c3db

Browse files
committed
Fix for graph legend not showing decimal places
1 parent 3f5ac8d commit 141c3db

File tree

1 file changed

+45
-3
lines changed

1 file changed

+45
-3
lines changed

apps/webapp/app/components/primitives/AnimatedNumber.tsx

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,51 @@
11
import { animate, motion, useMotionValue, useTransform } from "framer-motion";
2-
import { useEffect } from "react";
2+
import { useEffect, useMemo } from "react";
33

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+
}) {
532
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+
});
749

850
useEffect(() => {
951
animate(motionValue, value, {

0 commit comments

Comments
 (0)