Fix percent display at large values

This commit is contained in:
omuretsu
2023-02-18 08:03:16 -05:00
parent af0ed1dbb0
commit bd4fe19fde
3 changed files with 11 additions and 6 deletions

View File

@ -1691,10 +1691,11 @@ export const ns: InternalAPI<NSFull> = {
},
formatPercent:
(ctx) =>
(_n, _fractionalDigits = 2) => {
(_n, _fractionalDigits = 2, _suffixStart = 1e7) => {
const n = helpers.number(ctx, "n", _n);
const fractionalDigits = helpers.number(ctx, "fractionalDigits", _fractionalDigits);
return formatPercent(n, fractionalDigits);
const suffixStart = helpers.number(ctx, "suffixStart", _suffixStart);
return formatPercent(n, fractionalDigits, suffixStart);
},
// Todo: Remove function in 2.3. Until then it just directly wraps numeral.
nFormat: (ctx) => (_n, _format) => {

View File

@ -6456,9 +6456,10 @@ export interface NS {
*
* @param n - Number to format as a percentage.
* @param fractionalDigits - Number of digits to show in the fractional part of the decimal number. Optional, defaults to 2.
* @param suffixStart - When to attach a suffix to the percentage. Default is 1e7 which is 1b %.
* @returns Formatted percentage.
*/
formatPercent(n: number, fractionalDigits?: number): string;
formatPercent(n: number, fractionalDigits?: number, suffixStart?: number): string;
/**
* Format a number using the numeral library. This function is deprecated and will be removed in 2.3.

View File

@ -88,18 +88,21 @@ function formatExponential(n: number) {
return exponentialFormatter.format(n).toLocaleLowerCase();
}
export function formatPercent(n: number, fractionalDigits = 2) {
// Default suffixing starts at 1e9 % which is 1e7.
export function formatPercent(n: number, fractionalDigits = 2, suffixStart = 1e7) {
// NaN does not get formatted
if (Number.isNaN(n)) return "NaN%";
const nAbs = Math.abs(n);
// Special handling for Infinities
if (nAbs === Infinity) return n < 0 ? "-∞%" : "∞%";
if (nAbs * 100 === Infinity) return n < 0 ? "-∞%" : "∞%";
// Suffix form adds a space to be less visually confusing. Values this high should rarely be seen.
if (nAbs >= suffixStart) return formatNumber(n * 100, fractionalDigits, 0) + " %";
return getFormatter(fractionalDigits, percentFormats, { style: "percent" }).format(n);
}
// formatNumber doesn't accept ram as a special flag, that is only used for ns.formatNumber which will use formatRam
export function formatNumber(n: number, fractionalDigits = 3, suffixStart = 1000, isInteger = false) {
// NaN does not get formatted
if (Number.isNaN(n)) return "NaN";