Converting bytes size to kilobytes or megabytes

Sure! Here's an example JavaScript code for converting bytes to kilobytes or megabytes:

// Function to convert bytes to kilobytes or megabytes
function convertBytes(bytes, unit) {
  let units = {
    'B': 0,
    'KB': 1,
    'MB': 2,
  };
  let sizeInUnits = bytes / Math.pow(1024, units[unit]);
  return sizeInUnits.toFixed(2) + ' ' + unit;
}

// Example usage
let bytes = 5000000; // 5 MB
console.log(convertBytes(bytes, 'KB')); // Output: 4882.81 KB
console.log(convertBytes(bytes, 'MB')); // Output: 4.77 MB

In this code, the convertBytes function takes two arguments: bytes which is the size in bytes that you want to convert, and unit which is the unit that you want to convert to ('KB' for kilobytes or 'MB' for megabytes).

The function first defines an object called units which maps unit names to their respective powers of 1024. It then calculates the size in the desired unit by dividing the input bytes by 1024 raised to the power of the unit's exponent in the units object. Finally, it returns the size in the desired unit as a string with two decimal places.

The example usage at the bottom of the code shows how you can call the convertBytes function to convert a size of 5 MB to kilobytes and megabytes. The output should be approximately 4882.81 KB and 4.77 MB, respectively.

댓글

이 블로그의 인기 게시물

PYTHONPATH, Python 모듈 환경설정

You can use Sublime Text from the command line by utilizing the subl command

git 명령어

[gRPC] server of Java and client of Typescript

[Ubuntu] Apache2.4.x 설치

Create topic on Kafka with partition count, 카프카 토픽 생성하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Auto-populate a calendar in an MUI (Material-UI) TextField component

The pierce selector in Puppeteer