-3

How I can get numeric value from a string ?

Here are a few examples.

val1 = '18,000';    
val2 = '18,000 USD';  
val3 = '18,000 PKR';    
val4 = '18000 PKR';

I need to get only numbers, 18000 only. Nothing else.

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
  • 1
    Have you searched on using a regex? – tymeJV May 29 '13 at 17:12
  • 1
    This has already been asked in this site. Please take a look at this link : http://stackoverflow.com/questions/10003683/javascript-get-number-from-string – krishwader May 29 '13 at 17:13
  • 1
    and this : http://stackoverflow.com/questions/3955345/javascript-jquery-get-number-from-string – krishwader May 29 '13 at 17:14
  • 1
    these aren't strings – you need to quote them. – Beat May 29 '13 at 17:14
  • What language? PHP or Javascript? – Jocelyn May 29 '13 at 17:15
  • Oh damn im not able to stop myself. Here's one more : http://stackoverflow.com/questions/1130083/how-to-pull-a-number-out-of-a-string-in-javascript You mustve tried googling before posting. There's tons of stuff for this. (both JS and PHP solutions available) – krishwader May 29 '13 at 17:18

3 Answers3

0

try this:

 var num = Number(val1.replace(/[^0-9.]/g, ""));
Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
0

First you have to replace all commas in the string. Then you can use the JavaScript function parseInt.

var str = "18,000 USD";
str = str.replace(/,/g, "");
var num = parseInt(str, 10);
alert(num);

Now, if you want decimal places, you can use parseFloat.

var str2 = "18,000.50 USD";
str2 = str2.replace(/,/g, "");
var num2 = parseFloat(str2, 10);
alert(num2);

Working example: http://jsfiddle.net/arffD/1/

ktm5124
  • 11,861
  • 21
  • 74
  • 119
0

Assuming you make corrections to your code, you should be able to convert them to their real values with this

var val1 = "18,000";
var val2 = "18,000 USD";
var val3 = "18,000 PKR";
var val4 = "18000 PKR";

[val1, val2, val3, val4].map(function (n) { 
  return Number(n.replace(/[^\d]+/gi, '')) 
});

That should give you an array of values like this:

[ 18000,
  18000,
  18000,
  18000 ]

For PHP you could do this:

    $val1 = "18,000";
    $val2 = "18,000 USD";
    $val3 = "18,000 PKR";
    $val4 = "18000 PKR";

    function map ($n) {
        $n = preg_replace("%[^\d]+%mi", '', $n);
        return $n;
    }

    $vals = array_map(map, array($val1, $val2, $val3, $val4));

$vals will hold the real values and print_r($vals); should yield:

    Array
    (
        [0] => 18000
        [1] => 18000
        [2] => 18000
        [3] => 18000
    )