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.
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.
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/
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
)