Skip to content

OpenStock is an open-source alternative to expensive market platforms. Track real-time prices, set personalized alerts, and explore detailed company insights — built openly, for everyone, forever free.

fix: prevent "NaN" market cap when Finnhub omits the value

ravixalgorithmadecbd53bda1
diff --git a/__tests__/utils.test.ts b/__tests__/utils.test.ts
index 58ee746..49e6b71 100644
--- a/__tests__/utils.test.ts
+++ b/__tests__/utils.test.ts
@@ -5,6 +5,7 @@ import {
formatChangePercent,
getChangeColorClass,
calculateNewsDistribution,
+ formatNumber,
} from '@/lib/utils';
describe('formatSymbolForTradingView', () => {
@@ -187,6 +188,25 @@ describe('getChangeColorClass', () => {
});
});
+describe('formatNumber', () => {
+ // Finnhub's profile2 marketCapitalization is expressed in millions of USD,
+ // which formatNumber scales up by 1e6.
+ it('formats market caps (input in millions) into T/B/M/K suffixes', () => {
+ expect(formatNumber(3_000_000)).toBe('3.00T'); // 3,000,000M => $3T
+ expect(formatNumber(150_000)).toBe('150.00B'); // 150,000M => $150B
+ expect(formatNumber(150)).toBe('150.00M'); // 150M => $150M
+ });
+
+ it('returns N/A for missing or non-finite market caps', () => {
+ // Finnhub omits marketCapitalization for many symbols (e.g. ETFs); the
+ // watchlist passes that value straight through, so it must not render "NaN".
+ expect(formatNumber(undefined)).toBe('N/A');
+ expect(formatNumber(null)).toBe('N/A');
+ expect(formatNumber(NaN)).toBe('N/A');
+ expect(formatNumber(Infinity)).toBe('N/A');
+ });
+});
+
describe('calculateNewsDistribution', () => {
it('returns 3 items per symbol for 1-2 symbols', () => {
expect(calculateNewsDistribution(1).itemsPerSymbol).toBe(3);
diff --git a/lib/utils.ts b/lib/utils.ts
index 0539659..51bc448 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -119,7 +119,11 @@ export const formatPrice = (price: number, currency = 'USD') => {
// Alias for consistency
export const formatCurrency = formatPrice;
-export function formatNumber(num: number): string {
+export function formatNumber(num?: number | null): string {
+ // Guard against missing/invalid market caps (Finnhub omits this field for many
+ // symbols, e.g. ETFs). Without this, `num * 1e6` yields NaN and renders "NaN".
+ if (num === undefined || num === null || !Number.isFinite(num)) return 'N/A';
+
// If number is small (likely already in millions from Finnhub), multiply by 1M to get actual value
// Typical mega-cap is > 100B. 100B in millions is 100,000.
// If we assume typical market cap input IS millions: