JavaScript: Convert a number in bytes to a human-readable string
JavaScript fundamental (ES6 Syntax): Exercise-163 with Solution
Write a JavaScript program to convert a number in bytes to a human-readable string.
Note: Use an array dictionary of units to be accessed based on the exponent.
- Use an array dictionary of units to be accessed based on the exponent.
- Use Number.prototype.toPrecision() to truncate the number to a certain number of digits.
- Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not.
- Omit the second argument, precision, to use a default precision of 3 digits.
- Omit the third argument, addSpace, to add space between the number and unit by default.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const prettyBytes = (num, precision = 3, addSpace = true) => {
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);
const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));
return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
};
console.log(prettyBytes(1000));
console.log(prettyBytes(-27145424323.5821, 5));
console.log(prettyBytes(123456789, 3, false));
Sample Output:
1 KB -27.145 GB 123MB
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-163-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to convert an asynchronous function to return a promise.
Next: Write a JavaScript program that will return the singular or plural form of the word based on the input number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
JavaScript: Tips of the Day
Checking if a key exists in a JavaScript object?
Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?
var obj = { key: undefined }; obj["key"] !== undefined // false, but the key exists!
You should instead use the in operator:
"key" in obj // true, regardless of the actual value
If you want to check if a key doesn't exist, remember to use parenthesis:
!("key" in obj) // true if "key" doesn't exist in object !"key" in obj // ERROR! Equivalent to "false in obj"
Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:
obj.hasOwnProperty("key") // true
Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined? var obj = { key: undefined }; obj["key"] !== undefined // false, but the key exists! You should instead use the in operator: "key" in obj // true, regardless of the actual value If you want to check if a key doesn't exist, remember to use parenthesis: !("key" in obj) // true if "key" doesn't exist in object !"key" in obj // ERROR! Equivalent to "false in obj" Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty: obj.hasOwnProperty("key") // true For performance comparison between the methods that are in, hasOwnProperty and key is undefined.
Ref: https://bit.ly/2CFNp1X
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework