Changing second half of string number digits to zero using JavaScript


Problem

We are required to write a JavaScript function that takes in a string number as the only argument.

Our function should return the input number with the second half of digits changed to 0.

In cases where the number has an odd number of digits, the middle digit onwards should be changed to 0.

For example −

938473 → 938000

Example

Following is the code −

 Live Demo

const num = '938473';
const convertHalf = (num = '') => {
   let i = num.toString();
   let j = Math.floor(i.length / 2);
   if (j * 2 === i.length) {
      return parseInt(i.slice(0, j) + '0'.repeat(j));
   }else{
      return parseInt(i.slice(0, j) + '0'.repeat(j + 1));
   };
};
console.log(convertHalf(num));

Output

938000

Updated on: 21-Apr-2021

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements