Home > Software engineering >  How to Split number with comma after two digit and store into two variables in javascript?
How to Split number with comma after two digit and store into two variables in javascript?

Time:04-12

I have a variable var Number = 2425; I want to break it into two parts and store into into two different variables.

var data = 24;
var month = 25;

How can I get this in javaScript.

CodePudding user response:

Coerce the number to a string, and then use substring to get the relevant characters.

const number = 2425;

const str = String(number);

const data = str.substring(0, 2);
const month = str.substring(2);

console.log(data, month);

CodePudding user response:

You need to substring the number at target position and after that you can add comma and join the rest of the number . Then split it with comma and get as array. Then you can use the array at position . Check the below solution

function splitNumber(number, index) {
    var commaAdded = number.substring(0, index)   ','   number.substring(index);
    return commaAdded.split(',');
}

console.log(splitNumber('2425', 2));
// ["24", "25"]

Now you can use the array index in your variable.

CodePudding user response:

One was would be to convert it into a string and do a slice on it.

let num = 2524;
let strNum = String(num);
let midIndex = Math.floor(strNum.length/2);
let firstHalf = Number(strNum.slice(0,midIndex));
let secondHalf = Number(strNum.slice(midIndex));
console.log(firstHalf);
console.log(secondHalf);

CodePudding user response:

Or just math via treating "Number" as an arithmetic progression on order of 100:

var number = 2425
var data = Math.floor(number / 100)
var month = number - (data * 100)

console.log(number)
console.log(data)
console.log(month)

/* Output
2425
24
25
*/

But don't really understand how "month" can be more than 12, let alone 11 if base(0).

  • Related