
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 −
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
- Related Articles
- Changing the case of a string using JavaScript
- Sum of individual even and odd digits in a string number using JavaScript
- Reversed array of digits from number using JavaScript
- Rearranging digits to form the greatest number using JavaScript
- How to count digits of given number? JavaScript
- Convert number to reversed array of digits JavaScript
- Adding digits of a number using more than 2 methods JavaScript
- Reverse digits of an integer in JavaScript without using array or string methods
- Finding product of Number digits in JavaScript
- Separating digits of a number in JavaScript
- Remove all characters of first string from second JavaScript
- Dynamic Programming: Is second string subsequence of first JavaScript
- Find number of spaces in a string using JavaScript
- Repeating string for specific number of times using JavaScript
- Convert number to a reversed array of digits in JavaScript

Advertisements