0

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 ?

6
  • 2
    Technically, it should be 0.099 if I'm not wrong. What about using .toPrecision instead of .toFixed? Commented Jul 4, 2019 at 7:13
  • Increase b to be bigger, like 10 and see then. Seems like rounding problem Commented Jul 4, 2019 at 7:13
  • 1
    toFixed is doing the right thing, since the number is 0.099 but you wanted only the first 2 digits so 0.099 is rounded up to 0.10 to account for the x.xx9 that it couldn't display - if you want truncation rather than rounding, pretty sure that could be done with a little toString+substring trickery, though Commented Jul 4, 2019 at 7:13
  • more info about strange behaviour of toFixed can be found here and here Commented Jul 4, 2019 at 7:20
  • Good answers can also be found here Commented Jul 4, 2019 at 7:26

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to round off to 2 decimal places but still return accurate result, I dont think toPrecision also works. Is there any other alternative ?
The current behavior is the more accurate option, as 0.099 is closer to 0.10 then to 0.09. In this regard, it makes no different if you use toPrecision or toFixed
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.