Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,26 +225,31 @@ export function applyPrecisionHandling(
export function applyNumberFormatting(value, locale, localeOptions, separator, pad, round) {
let result = value;

// When padding alongside a locale, let the locale formatter emit the fixed
// number of fraction digits. The manual string padding below cannot tell a
// locale-inserted grouping separator from the decimal separator, so it
// dropped digits (e.g. "1,234,500" became "1,234").
const localePad =
pad && round > 0 ? { minimumFractionDigits: round, maximumFractionDigits: round } : undefined;

// Apply locale formatting
if (locale === true) {
result = result.toLocaleString();
result = result.toLocaleString(undefined, localePad);
} else if (locale.length > 0) {
result = result.toLocaleString(locale, localeOptions);
result = result.toLocaleString(locale, { ...localeOptions, ...localePad });
} else if (separator.length > 0) {
result = result.toString().replace(PERIOD, separator);
}

// Apply padding
if (pad && round > 0) {
// Apply padding for the non-locale paths, where the string has a single
// decimal separator and no grouping is inserted.
if (pad && round > 0 && locale !== true && locale.length === 0) {
const resultStr = result.toString();
const x = separator || (resultStr.slice(1).match(/[.,]/g) || []).pop() || PERIOD;
const x = separator || PERIOD;
const tmp = resultStr.split(x);
const s = tmp[1] || EMPTY;

const l = s.length;
const n = round - l;

result = `${tmp[0]}${x}${s.padEnd(l + n, ZERO)}`;
result = `${tmp[0]}${x}${s.padEnd(round, ZERO)}`;
}

return result;
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/filesize.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,17 @@ describe("filesize", () => {
assert.strictEqual(filesize(1234567, { locale: "en-US", pad: true, round: 2 }), "1.23 MB");
assert.strictEqual(filesize(1234567890, { locale: "en-US", pad: true, round: 2 }), "1.23 GB");
});

it("should keep every digit group and pad when an integer value has grouping separators", () => {
// en: comma grouping with no decimal in the raw value. Previously the
// trailing grouping comma was mistaken for the decimal separator, which
// dropped digit groups and skipped padding.
assert.strictEqual(
filesize(1234500e24, { locale: "en", pad: true, round: 2 }),
"1,234,500.00 YB",
);
assert.strictEqual(filesize(1000e24, { locale: "en", pad: true, round: 2 }), "1,000.00 YB");
});
});

describe("Custom separators and spacers", () => {
Expand Down
Loading