2022-10-25 21:35:32 +00:00
|
|
|
export const abbrNum = n => {
|
2022-02-17 17:23:43 +00:00
|
|
|
if (n < 1e4) return n
|
|
|
|
if (n >= 1e4 && n < 1e6) return +(n / 1e3).toFixed(1) + 'k'
|
|
|
|
if (n >= 1e6 && n < 1e9) return +(n / 1e6).toFixed(1) + 'm'
|
|
|
|
if (n >= 1e9 && n < 1e12) return +(n / 1e9).toFixed(1) + 'b'
|
|
|
|
if (n >= 1e12) return +(n / 1e12).toFixed(1) + 't'
|
|
|
|
}
|
2022-07-30 13:25:46 +00:00
|
|
|
|
2023-08-08 21:04:06 +00:00
|
|
|
/**
|
|
|
|
* Take a number that represents a count
|
|
|
|
* and return a formatted label e.g. 0 sats, 1 sat, 2 sats
|
|
|
|
*
|
|
|
|
* @param n The number of sats
|
|
|
|
* @param opts Options
|
|
|
|
* @param opts.abbreviate Whether to abbreviate the number
|
|
|
|
* @param opts.unitSingular The singular unit label
|
|
|
|
* @param opts.unitPlural The plural unit label
|
2023-09-18 22:49:13 +00:00
|
|
|
* @param opts.format Format the number with `Intl.NumberFormat`. Can only be used if `abbreviate` is false
|
2023-08-08 21:04:06 +00:00
|
|
|
*/
|
|
|
|
export const numWithUnits = (n, {
|
|
|
|
abbreviate = true,
|
|
|
|
unitSingular = 'sat',
|
2023-09-18 22:49:13 +00:00
|
|
|
unitPlural = 'sats',
|
|
|
|
format = false
|
2023-08-08 21:04:06 +00:00
|
|
|
} = {}) => {
|
|
|
|
if (isNaN(n)) {
|
|
|
|
return `${n} ${unitPlural}`
|
|
|
|
}
|
2023-09-18 22:49:13 +00:00
|
|
|
return `${abbreviate ? abbrNum(n) : format ? new Intl.NumberFormat().format(n) : n} ${n === 1 ? unitSingular : unitPlural}`
|
2023-08-08 21:04:06 +00:00
|
|
|
}
|
|
|
|
|
2022-07-30 13:25:46 +00:00
|
|
|
export const fixedDecimal = (n, f) => {
|
|
|
|
return Number.parseFloat(n).toFixed(f)
|
|
|
|
}
|
2022-11-15 20:51:55 +00:00
|
|
|
|
|
|
|
export const msatsToSats = msats => {
|
|
|
|
if (msats === null || msats === undefined) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
return Number(BigInt(msats) / 1000n)
|
|
|
|
}
|
2022-12-19 22:27:52 +00:00
|
|
|
|
2024-01-07 17:00:24 +00:00
|
|
|
export const satsToMsats = sats => {
|
|
|
|
if (sats === null || sats === undefined) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
return BigInt(sats) * 1000n
|
|
|
|
}
|
|
|
|
|
2022-12-19 22:27:52 +00:00
|
|
|
export const msatsToSatsDecimal = msats => {
|
|
|
|
if (msats === null || msats === undefined) {
|
|
|
|
return null
|
|
|
|
}
|
2023-07-27 00:18:42 +00:00
|
|
|
return fixedDecimal(Number(msats) / 1000.0, 3)
|
2022-12-19 22:27:52 +00:00
|
|
|
}
|