0

I am trying to add a conversation logic for converting 1 GB to value 1000; 2.5 GB to value 2500; 50 MB to value 50; 1 MB to value 1 and so on using javascript.

I tried adding logic but it is comprising multiple if else.

var bw;
var value;
if (bw.toUpperCase() == '1 GB' || bw.toUpperCase() == '1 GBPS')
{
  value = 1000;
}
else if (bw.toUpperCase() == '2.5 GB' || bw.toUpperCase() == '2.5 GBPS')
{
  value = 2500;
}

and so on for MB. The only values that will come are GB or MB. No kb or bytes.

  • With your logic, you need to add a lot of cases in your `if-else` clause. Why don't you parse the input string and multiply the value by 1000? Also, `w` is undefined. – Raptor Jun 14 '22 at 07:46
  • Does this answer your question? [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) – Himanshu Poddar Jun 14 '22 at 07:47

1 Answers1

1

One option is:

let units = { GB: 1000, GBPS: 1000, ... };
let [a, b] = yourString.split(' ');
let value = +a * units[b];
Ram
  • 143,282
  • 16
  • 168
  • 197