
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change 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 −
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
Advertisements