0

I am creating a web app in which I want to convert bytes int kb,mb.gb,tb. (As per dropdownlistt)

here is how my code looks

function changebyteintoselectedValue(bytes, si){
  var thresh = si ? 1000 : 1024;
  if(Math.abs(bytes) < thresh) {
      return bytes + ' B';
  }
  var units = si
      ? ['kB','MB','GB','TB','PB','EB','ZB','YB']
      : ['KB','MB','GB','TB','PB','EB','ZB','YB'];
  var u = -1;
  do {
      bytes /= thresh;
      ++u;
  } while(Math.abs(bytes) >= thresh && u < units.length - 1);
  alert(bytes.toFixed(1)+' '+units[u]);
}
<select onchange="changebyteintoselectedValue(123123123)">
  <option value="KB">KB</option>
  <option value="MB">MB</option>
  <option value="GB">GB</option>
  <option value="TB">TB</option>
</select>

I want to convert as per user need, but now it is directly converting into mb,

how can I convert bytes as per user selection?

  • 1
    You need to read the value of your drop down. You don't seem to be doing that anywhere. – Kei Sep 23 '19 at 10:22
  • Possible duplicate of [Correct way to convert size in bytes to KB, MB, GB in JavaScript](https://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript) – sayalok Sep 23 '19 at 10:24
  • 2
    The units for 1024 should probably be [Kib,MiB,GiB,TiB,PiB,EiB,ZiB,YiB](https://en.wikipedia.org/wiki/Kibibyte) to make it clear that they are not SI units. – some Sep 23 '19 at 10:33
  • I second what @Kei said. This might help: https://stackoverflow.com/questions/5024056/how-to-pass-parameters-on-onchange-of-html-select – a_nain Sep 23 '19 at 10:35

0 Answers0