-5

I am new in Javascript and I don't know much about the js programming. I am thinking of separate 12.13 into two-part 12 and 13 from the dot in javascript.

I found on the website separate string into two-part but I don't know how to do with the integer. For example,

var i = "12.13"
var t = i.split(""); 
TulMagar
  • 49
  • 1
  • 8

3 Answers3

2

If the given number is already a string, then you can directly split it using .split() otherwise, convert the number to a string using .toString() then .split() it.

String#split accepts a separator as its first parameter.

var number = "12.13";
var split = number.split(".");

console.log(split[0]);
console.log(split[1]);
Rin Minase
  • 308
  • 2
  • 5
  • 19
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • And to convert split values to numbers, you could just map on `Number`, i.e. `i.split(".").map(Number)` --> `[12, 13]` – Jayce444 Sep 16 '19 at 05:33
0

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] 
Vitim.us
  • 20,746
  • 15
  • 92
  • 109
0

Split by a dot (.) but not by a blank string. After splitting you get the list of number as an array. See the reference split()

var i = "12.13"
var t = i.split("."); 
console.log(t)

And now if you want to get the parts to two separate variable

var i = "12.13"
var t = i.split(".").map(Number); // map() is to convert the string to number

var part1 = t[0]
var part2 = t[1]

console.log(part1, part2)
MH2K9
  • 11,951
  • 7
  • 32
  • 49