user804401
user804401

Reputation: 1994

Convert bytes to TB returns incorrect value

Currently I have a function to convert bytes too TB.

I am using the below formula to convert.

const formatBytesToTB = (a, b = 2) => {
  if (a === 0) {
    return "0 TB";
  }
  return (a / 1099511627776).toFixed(b) + " TB";
};
console.log(formatBytesToTB(109213384704));

The above function is working fine for most of the values that it accepts as bytes

I see some error when bytes value is less than 1 TB.

For example when the input is "109213384704” the function returns “0.10 TB”

Expected output should be “0.09”

I have seen few online converters to test what they return, Google returns 0.10 but rest of the converters show 0.09

Is the function doing right thing ?

Upvotes: 0

Views: 309

Answers (2)

Tushar Gupta
Tushar Gupta

Reputation: 15923

109213384704 is 0.099 In Tebibyte(TiB) and 0.10 Terrabyte (TB).

From definitions:

How large is a tebibyte? A tebibyte is larger than the following binary data capacity measures:

  • A byte -- a TiB is equal to 1,099,511,627,776 bytes.
  • A kibibyte (KiB) -- a TiB is equal to 1,073,741,824 KiB.
  • A mebibyte (MiB) – a TiB is equal to 1,048,576 MiB.
  • A gibibyte -- a TiB is equal to 1,024 GiB.

Upvotes: 1

yuval.bl
yuval.bl

Reputation: 5074

It seems like a matter of display - Rounding vs Ignoring the decimal after precision value.

The value of 109213384704 / 1099511627776 is 0.099328995

So if you would like to simply ignore whatever comes after the second decimal point, you'll get 0.09.

However,toFixed will round the number to the precision value, so 0.099 will result 0.10 while 0.091 will result with 0.09.

Upvotes: 1

Related Questions