Skip to content

fix: precision leaves 1000 kB in the old unit and rounds to round before the unit bump #413

Open

Description

@bardrop

Summary

Two problems in the precision path when the value moves to the next unit (applyPrecisionHandling):

  1. Since 11.0.31 (fix: apply precision before round for decimal units #404), a value that rounds up to the unit ceiling stays in the old unit: filesize(999999, { precision: 4 }) prints 1000 kB, while filesize(999999) prints 1 MB. 11.0.30 printed 1.000 MB. The unit only moves when toPrecision() returns e-notation, and (999.999).toPrecision(4) is "1000".
  2. When the unit does move, the new value is rounded to round decimals before toPrecision() runs. This is the same double rounding fix: precision is applied after round, rounding an already-rounded value #399 fixed in the main path. With round: 0 it even prints 0: filesize(392, { precision: 1, round: 0 }) gives 0 kB.

Reproduction

  1. Run the code sample below with node repro.mjs.

Expected Behavior

1.000 MB
1.000 MiB
0.977 MiB
0.986 GiB
0.4 kB

Actual Behavior

1000 kB
1024 KiB
0.980 MiB
0.990 GiB
0 kB

Environment

  • Node.js version: v24.10.0
  • OS: macOS (arm64)
  • filesize.js version: 11.0.32 (master at c422438)

Code Sample

import { filesize } from "filesize";

console.log(filesize(999999, { precision: 4 }));                // 999.999 kB -> "1000" -> stays kB
console.log(filesize(1048575, { base: 2, precision: 4 }));      // 1023.999 KiB -> "1024" -> stays KiB
console.log(filesize(1024000, { base: 2, precision: 3 }));      // 0.9766 MiB, rounded to 0.98 first
console.log(filesize(1058223158, { base: 2, precision: 3 }));   // 0.9855 GiB, rounded to 0.99 first
console.log(filesize(392, { precision: 1, round: 0 }));         // 0.392 kB, rounded to 0 first

Additional Context

In applyPrecisionHandling() (src/helpers.js) the bump runs only on result.includes(E), and the recomputed value goes through roundingFunc(valueResult * p) / p before toPrecision(). The existing test "should handle precision with specific test case for GiB values" pins 0.990 GiB, but 1058223158 / 2^30 = 0.98555. I have a fix ready and will open a PR.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions