Skip to content

Commit

Permalink
add parse_si_float
Browse files Browse the repository at this point in the history
basically the inverse to pretty_num
  • Loading branch information
janosh committed Jul 19, 2024
1 parent fb8a4c3 commit 566cc48
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/lib/labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,16 @@ export const pretty_num = (num: number, fmt?: string | number) => {
}
return format(fmt)(num)
}

// basically the inverse to pretty_num
export function parse_si_float(value: string): number | string {
export function parse_si_float<T extends string | number | null | undefined>(
value: T,
): T | number | string {
// if not string, return as is
if (typeof value !== `string`) return value
// Remove any whitespace
value = value.trim()
// Remove whitespace and commas
const cleaned = value.trim().replace(/(\d),(\d)/g, `$1$2`)

// Check if the value is a SI-formatted number (e.g., "1.23k", "4.56M", "789µ", "12n")
const match = value.match(/^([-+]?\d*\.?\d+)\s*([yzafpnµmkMGTPEZY])?$/i)
const match = cleaned.match(/^([-+]?\d*\.?\d+)\s*([yzafpnµmkMGTPEZY])?$/i)
if (match) {
const [, num_part, suffix] = match
let multiplier = 1
Expand All @@ -79,6 +80,11 @@ export function parse_si_float(value: string): number | string {
return parseFloat(num_part) * multiplier
}

// If it's a number without SI suffix, try parsing it
if (/^[-+]?[\d,]+\.?\d*$/.test(cleaned)) {
return parseFloat(cleaned)
}

// If the value is not a formatted number, return as is
return value
}
Expand Down

0 comments on commit 566cc48

Please sign in to comment.