Search code examples
javascriptecmascript-6filesize

byte to human readable size with npm package filesize


I need to convert megabytes to the appropriate unit.

parseInt(10000) * 1024 * 1024 //10485760000 byte

filesize(parseInt(10000) * 1024 * 1024); // "9.77 GB"

9.77 GB seems to be wrong. When I convert it using google converter online i get:

10485760000 Byte = 10,48576 Gigabyte

Why is this packages behavor like this?


Solution

  • The SI units are (mostly) based on decimal fractions, so do their prefixes:

    • kilo (K): 103 = 1,000
    • mega (M): 106 = 1,000,000
    • giga (G): 109 = 1,000,000,000

    When digital base 2 computers were developed they invented new prefixes. Agreement about values was soon reached but it wasn't easy to find catchy names. Unfortunately, the names that eventually spread where the SI ones, so we ended up with a nice confusion:

    • kilo (K): 210 = 1,024
    • mega (M): 220 = 1,048,576
    • giga (G): 230 = 1,073,741,824

    Then, someone invented some new names that were arguably not as bad as previous ones, but it was too late and almost nobody uses them:

    • kibi (Ki): 210 = 1,024
    • mebi (Mi): 220 = 1,048,576
    • gibi (Gi): 230 = 1,073,741,824

    In computers almost everything is a power of 2 so decimal-based units are usually avoided because they are never round.

    In your example, using base 2 and base 10 prefixes renders this:

    • 10485760000 / 230 = 9.765625 GiB
    • 10485760000 / 109 = 10.48576 GB

    The value you want it probably the first one given that it's a file size.