convert a number from base 2 to base 10 in typescript

To convert a binary number to decimal (base 2 to base 10) in TypeScript, you can use the following function:

index.ts
function binaryToDecimal(binary: string): number {
  let decimal = 0;
  let binaryDigit = parseInt(binary, 10);
  let base = 1;

  while (binaryDigit > 0) {
    let lastDigit = binaryDigit % 10;
    binaryDigit = Math.floor(binaryDigit / 10);
    decimal += lastDigit * base;
    base *= 2;
  }

  return decimal;
}
316 chars
15 lines

To use this function, you can pass in a binary number as a string and it will return the equivalent decimal number as a number data type.

For example:

index.ts
console.log(binaryToDecimal("1010")); // output: 10
console.log(binaryToDecimal("110010")); // output: 50
106 chars
3 lines

gistlibby LogSnag