Erik
Erik

Reputation: 14770

How to parse two space-delimited numbers with thousand separator?

I need to parse string that contains two numbers that may be in three cases :

"646.60 25.10" => [646.60 25.10]

"1 395.86 13.50" => [1395.86, 13.50]

"13.50 1 783.69" => [13.50, 1 783.69]

In a simple case it's enough use 'number'.join(' ') but in the some cases there is thousand separator like in second and third ones.

So how could I parse there numbers for all cases?

EDIT: All numbers have a decimal separator in the last segment of a number.

Upvotes: 0

Views: 167

Answers (2)

et_l
et_l

Reputation: 1908

Assuming every number ends with a dot-digit-digit (in the comments you said they do), you can use that to target the right place to split with aregex. That way, it is robust and general for any number of numbers (although you specified you have only two) and for any number of digits in the numbers, as long as it ends with the digit-dot-digit-digit:

str1 = "4 435.89 1 333 456.90 7.54";

function splitToNumbers(str){
  arr = str.replace(/\s+/g,'').split(/(\d+.\d\d)/);
  //now clear the empty strings however you like
  arr.shift();
  arr.pop();
  arr = arr.join('&').split(/&+/);

 return arr;
}

console.log(splitToNumbers(str1));
//4435.89,1333456.90,7.54

Upvotes: 0

Ben Cummins
Ben Cummins

Reputation: 508

var string1 = "646.60 25.10";// => [646.60 25.10]

var string2 = "1 395.86 13,50";// => [1395.86, 13,50]

var string3 = "13.50 1 783.69"; // => [13.50, 1 783.69]


function getArray(s) {
var index = s.indexOf(" ", s.indexOf("."));
	return [s.substring(0,index), s.substring(index+1) ];
}


console.log(getArray(string1));
console.log(getArray(string2));
console.log(getArray(string3));

Upvotes: 3

Related Questions