Just starting out with Javascript and coding, I'm having trouble squaring a number that comes from a function. I've outlined below what I am trying to achieve. Thank you in advance for your help.
// CONVERT BINARY TO DECIMAL
// (100110)2 > (1 × 2⁵) + (0 × 2⁴) + (0 × 2³) + (1 × 2²) + (1 × 2¹) + (0 × 2⁰) = 38
let binary= prompt("Write a Binary Number");
function binaryToDecimalConverter(binary){
let decimal=0;
let power=0;
for(let i=binary.length-1; i>=0; i--){
decimal+=Number(binary.charAt(i)) * Math.pow(2,power);
power++;
}
console.log("Decimal : " + decimal);
console.log(squareIt(decimal));
}
binaryToDecimalConverter(binary);
function squareIt(decimal){
let sNumber=decimal.toString();
let total=0;
for(let i=sNumber.length-1; i>=0; i--){
total+=Number(sNumber.charAt(i))*Math.pow(Number(sNumber.charAt(i)),2);
}
return total;
}
I am attempting to convert a binary number entered by the user to decimal. Additionally, I am looking to square each digit of that number and then sum them up.