Skip to content

fix: stop dropping digits when pad is combined with a locale#292

Open
spokodev wants to merge 1 commit into
avoidwork:masterfrom
spokodev:fix-pad-locale-grouping
Open

fix: stop dropping digits when pad is combined with a locale#292
spokodev wants to merge 1 commit into
avoidwork:masterfrom
spokodev:fix-pad-locale-grouping

Conversation

@spokodev

Copy link
Copy Markdown

When pad is combined with locale, the padding step infers the decimal separator by taking the last ./, in the already-localized string:

// src/helpers.js, applyNumberFormatting
const x = separator || (resultStr.slice(1).match(/[.,]/g) || []).pop() || PERIOD;
const tmp = resultStr.split(x);

For a value the locale renders with grouping separators and no decimal part, that last separator is a grouping separator, so split produces several parts and only the first two are used. Digit groups are dropped and padding is skipped, so the formatted string no longer represents the value:

filesize(1234500e24, { locale: "en", pad: true, round: 2 })
// "1,234 YB"  — "500" lost, no padding; expected "1,234,500.00 YB"
filesize(1000e24, { locale: "en", pad: true, round: 2 })
// "1,000 YB"  — expected "1,000.00 YB"

The fix lets the locale formatter emit the fixed number of fraction digits via minimumFractionDigits / maximumFractionDigits, so the localized string is never re-parsed. The manual string padding now runs only for the non-locale paths (plain / custom separator), where the string has a single decimal separator and no grouping. The documented non-locale example (filesize(1536, {round: 3, pad: true})1.536 kB) and the existing locale tests are unchanged.

Full suite passes (171); added a regression test for the integer-with-grouping case.

(dist/ left unbuilt so the diff stays reviewable; happy to rebuild it if you prefer.)

When `pad` is used together with `locale`, the padding step inferred the
decimal separator by taking the last `.`/`,` in the already-localized
string. For a value the locale renders with grouping separators and no
decimal part, that last separator is a grouping separator, so splitting on
it dropped digit groups and skipped padding:

    filesize(1234500e24, {locale: 'en', pad: true, round: 2})
    // '1,234 YB'  (lost '500', no padding) — expected '1,234,500.00 YB'

Let the locale formatter emit the fixed number of fraction digits via
`minimumFractionDigits`/`maximumFractionDigits`, so the localized string is
never re-parsed. The manual string padding now runs only for the non-locale
paths (plain / custom separator), where the string has a single decimal
separator. Full suite passes (171); added a regression test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant