[BUG] filesize.decimal and DownloadColumn show 1,000.0 kB instead of 1.0 MB near unit boundaries

Open Beginner friendly
#4,257 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
82/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Start by reading the filesize unit-selection and formatting code, especially _to_str and pick_unit_and_suffix, then find or add tests for filesize.decimal and DownloadColumn at unit boundaries. Reproduce the reported values and check that rounding across a boundary selects the next unit while nearby values retain their current unit.

Written by the indexing model from the issue text.

Description

Describe the bug

rich.filesize.decimal picks the unit before rounding, so values just below a unit boundary get rounded up to "1,000.0" of the smaller unit instead of moving to the next unit:

from rich import filesize

print(filesize.decimal(999_499))      # 999.5 kB    (fine)
print(filesize.decimal(999_950))      # 1,000.0 kB  (expected 1.0 MB)
print(filesize.decimal(999_999))      # 1,000.0 kB  (expected 1.0 MB)
print(filesize.decimal(999_999_999))  # 1,000.0 MB  (expected 1.0 GB)

filesize.pick_unit_and_suffix has the same boundary check, so it shows up in progress bars too:

from rich.progress import DownloadColumn, Progress

progress = Progress(DownloadColumn())
progress.add_task("download", total=999_999, completed=999_999)
print(DownloadColumn().render(progress.tasks[0]).plain)  # 1,000.0/1,000.0 kB

The cause is that _to_str compares the raw size against base**i but then formats size / unit with precision digits, which can round up to base. One possible fix is to move to the next unit when the rounded value would reach base, e.g. compare round(size / unit_below, precision) < base when choosing the unit. I'm happy to send a PR with tests if this approach sounds OK.

(Related, smaller: negative sizes are never scaled, since size < base is always true for them: filesize.decimal(-5_000_000) returns '-5,000,000 bytes'. I can leave that out of scope if you'd prefer.)

Platform

Click to expand

Windows 11, reproduced with rich 15.0.0 from PyPI and with current master (3a109cc). This is independent of the terminal since it's pure string formatting.

Dominant language
Python
Stars
57.8k
Forks
2.6k
Avg merge
20m
Merged PRs (30d)
3

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Textualize/rich

All issues in Textualize/rich

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.