Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
How It Works
The algorithm works by calculating the midpoint of the string. For even-length strings, exactly half the digits are preserved. For odd-length strings, the middle digit becomes part of the second half that gets zeroed out.
Example
Following is the code:
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));
938000
Testing Multiple Cases
Let's test the function with different string lengths:
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('1234')); // Even length (4 digits)
console.log(convertHalf('12345')); // Odd length (5 digits)
console.log(convertHalf('678901')); // Even length (6 digits)
console.log(convertHalf('9')); // Single digit
1200 12000 678000 0
Simplified Version
Here's a more concise implementation:
const convertHalfSimple = (num = '') => {
const str = num.toString();
const halfPoint = Math.floor(str.length / 2);
return parseInt(str.slice(0, halfPoint) + '0'.repeat(str.length - halfPoint));
};
console.log(convertHalfSimple('938473'));
console.log(convertHalfSimple('12345'));
938000 12000
Key Points
-
Math.floor(length / 2)determines where to split the string - For even lengths: first half preserved, second half zeroed
- For odd lengths: middle digit becomes part of the zeroed section
-
slice(0, halfPoint)extracts the first half to keep -
'0'.repeat(count)generates the required zeros
Conclusion
This function effectively converts the second half of any numeric string to zeros using string slicing and the repeat method. The Math.floor operation handles both even and odd length strings correctly.
