-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathNumberDisplay.tsx
48 lines (42 loc) · 1.43 KB
/
NumberDisplay.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React from "react";
import { Tooltip } from "@kleros/ui-components-library";
import { commify } from "utils/commify";
interface INumberDisplay {
value: string | number;
unit?: string;
showUnitInDisplay?: boolean;
decimals?: number;
place?: "bottom" | "top" | "left" | "right";
isCurrency?: boolean; //currency units are shown in front
}
const getFormattedValue = (value: number, decimals: number) => {
const withFixedDecimals = value % 1 !== 0 ? value.toFixed(decimals) : value.toFixed(0);
if (value !== 0) {
if (withFixedDecimals === `0.${"0".repeat(decimals)}`) {
return `< 0.${"0".repeat(decimals - 1)}1`;
} else if (withFixedDecimals === `-0.${"0".repeat(decimals)}`) {
return `> -0.${"0".repeat(decimals - 1)}1`;
}
}
return commify(withFixedDecimals);
};
const NumberDisplay: React.FC<INumberDisplay> = ({
value,
unit,
place,
decimals = 2,
showUnitInDisplay = true,
isCurrency = false,
}) => {
const parsedValue = Number(value);
const formattedValue = getFormattedValue(parsedValue, decimals);
const tooltipValue = isCurrency ? `${unit} ${commify(value)}` : `${commify(value)} ${unit}`;
const displayUnit = showUnitInDisplay ? unit : "";
const displayValue = isCurrency ? `${displayUnit} ${formattedValue}` : `${formattedValue} ${displayUnit}`;
return (
<Tooltip small text={tooltipValue} place={place}>
{displayValue}
</Tooltip>
);
};
export default NumberDisplay;