Use the String.split() method.
If you have a number like 3.14
instead of "3.14"
you first need to convert it to a string. calling String(3.14)
or (3.14).toString()
or ""+3.14
.
Then call the method split() passing what you want to split the string by split('.')
Then you will end up with an array of sub strings like ["3", "14"]
.
Access each position of the array and convert it back to numbers if you want.
Number(arr[0])
or parseInt(arr[0])
or +arr[0]
or arr[0]|0
var i = 12.13;
var arr = String(i).split('.'); //convert the number to string, and then split the string by `.` into an array
var part1 = parseInt(arr[0], 10); //get the first element and convert into a integer
var part2 = parseInt(arr[1], 10); //get the second element and convert into a integer
console.log(part1); // 12
console.log(part2); // 13
If you want a one-liner
String("3.14").split(".").map(Number)
Alternatively you can also use RegExp. Use the index array[1]
and array[2]
instead
"3.14".match(/(\d+)\.(\d+)/).map(Number) // [3.14, 3, 14]