What is the method for transforming negative byte values into megabytes, gigabytes, and beyond?

One challenge I am facing in my Angular application is converting bytes to units such as MB, GB, etc.

The data I need for conversion is coming from the backend. For instance, I have data on All RAM, Available RAM, and Used RAM. These values are stored as integers, and I am simply trying to convert them. The formula for "Available RAM" is calculated by subtracting Used RAM from All RAM, and sometimes this results in a negative value which should be valid in our context.

However, the current function I am using does not handle negative values correctly.

Here is the function snippet:

 const SIZES = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

 formatBytes(bytes, decimals = 1) {
    for (var i = 0, r = bytes, b = 1024; r > b; i++) r /= b;         
    return `${parseFloat(r.toFixed(decimals))} ${SIZES[i]}`;
  }

I attempted to include an if statement checking for bytes < 0, but unfortunately that did not resolve the issue.

Answer №1

One possible solution to this problem could be to utilize the Math.abs() function:

const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
      formatData = (size, decimals) => {
        const unitIndex = units.findIndex((_,i) => Math.abs(size) < 1024**i)-1
        return `${((0|10**decimals*size/1024**unitIndex)/10**decimals)} ${units[unitIndex]}`
      }
      
console.log(formatData(-38750,2))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Troubleshooting issues with $.ajax not functioning correctly after being invoked with

I am facing an issue with my code. It works perfectly fine when I call AA.sendRequest() from the console, but encounters an error when I call it from an onclick event: <a href="/b/Technology" onclick="AA.sendRequest()">Technology</a> Somehow, ...

jQuery function for loading twice

Hey there, I have a question about the two load functions. Can anyone assist me? $(document).ready(function() { $('#link').click(function () { $("#top_menu").load("menu.php"); $("#content").load("content.php"); retur ...

What are the top techniques for designing with Angular 2 Material Design?

As a newcomer to angular 2 material design, I have noticed the primary, accent, and warn classes that apply specific colors to elements. Are these the only styling options available in Angular Material 2? Are there other classes that can be utilized for cu ...

Tips for organizing and nesting form data

Can I format my data in JSON like this: { attachments: { file: [ { name: 'pic1.jpg' }, { name: 'pic2.png' } ], username: 'Test', age: 1 } } Is it achievable us ...

Having trouble with Vuex actions. Getting an error message that says "Failed to signInWithEmailAndPassword: The first argument "email" must be a valid string."

I recently started exploring Vuejs state management. I attempted to create a login system with Firebase using Vuex. However, I encountered the following error: signInWithEmailAndPassword failed: First argument "email" must be a valid string I'm havi ...

Is there a way to make the components declared in entryComponents accessible to other modules for exporting?

Is it possible to dynamically create a component in app.module when the component is declared in the entryComponents section of app.module? // page.module.ts @NgModule({ declarations: [ ... DynamicComponent ], **entryCompone ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...

Filtering Angular routing history elements

If I have an application that relies on Router for navigation, is there a way to eliminate certain router history elements from the history? For example, is it possible to programmatically filter out all URLs containing 'xyz' like this: // Exampl ...

What is the process for assigning a background color to a specific option?

Trying to create a dropdown menu with various options and colors. Managed to set background colors for each option, but once an option is selected, the background color disappears. Is there a way to fix this issue? See my HTML example below: <select> ...

Arrange the row information in the MUI DataGrid in order to prepare it for exporting to CSV or Excel

Is there a way to organize row data for exporting to CSV or Excel with the MUI DataGrid? Take a look at my code snippet for the toolbar. slots={{ noRowsOverlay: NoDataComponent, noResultsOverlay: NoDataComponent, toolbar: ( ...

Is it possible to use jQuery's .load method (or $.ajax) for extracting and updating the page title

Up to this point... $('#container').load(hash + ' #page','', function() { $('#container').fadeIn('fast'); document.title = $('#title').load(hash + ' #title').text(); }); . ...

Is it considered best practice to update the state of a React component by calling a function from within another function?

Initially, my code is functional, but I'm interested in learning best practices as I am new to React. I aim to create a basic countdown feature, however, encountered problems while using this.setState(...) as 'this' was not defined. The ...

Errors related to missing RxJS operators are occurring in the browser, but are not showing up in Visual Studio

Recently, I encountered a peculiar problem with my Angular4 project, which is managed under Angular-CLI and utilizes the RxJS library. Upon updating the RxJS library to version 5.5.2, the project started experiencing issues with Observable operators. The s ...

How can I ensure that my Vue components do not interfere with each other's data when they are

Scenario Consider the following vue component: <template> <div> <slot>{{ title }}</slot> <ul> <li v-for="label in labels" :key="label"> <input type="checkbox ...

Notification for radio button selected

Looking to trigger an alert message when a radio button is not selected? Check out the code below: <form method=post name="spendform" id="spendform"> <input name="price" type="radio" class="invest-coin-check" id="pricemethod" > <button typ ...

Here is a unique version: "A guide on centering a carousel item in jquery upon being clicked."

Does anyone know how to center the item I click in a carousel? I've searched high and low for a solution but couldn't find a clear answer. Can someone please assist me with this? This is what I have tried so far: http://jsfiddle.net/sp9Jv/ Here ...

Automatically deducing types from object keys in Typescript is a convenient feature

I'm looking to define an interface for a Select component that allows for selecting single or multiple items. interface MySelect<T extends boolean> { multi: T, // Indicates if it's a multiple item select onChange: (item: T extends t ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

Taking an object out of a Group will also remove it from the Scene

Currently, I am working with a ThreeJS Group object in my scene. Adding and manipulating objects within the group works perfectly. However, whenever I attempt to remove an object from the group, it ends up getting entirely deleted from the scene. var ta ...

The functionality of mouse hover in multimaterial three.js appears to be not functioning

I'm facing an issue where I want to create a mouse hover effect on an object with multiple materials. See an example here function update() { // Finding intersections // Creating a Ray with the origin at the mouse position // and dire ...