I have string like
11.7 km
and I need get only int( 11.7 ), how can I do this with JavaScript?
Thanks.
I have string like
11.7 km
and I need get only int( 11.7 ), how can I do this with JavaScript?
Thanks.
Try the parseInt(). Example:
var string = "11.7 km";
alert(parseInt(string));
This would alert: "11".
In your case you have a float, so you could use:
alert(parseFloat(string));
This gives an alert with "11.7".
You can use replace
method by passing a regex
expression as argument.
console.log('11.7 km'.replace(/[^0-9.]/g, ''));
Try This.
var numbers = distance.replace(/[^0-9.]/g,'');
alert(numbers);
You can also use this.
console.log(Number(("11.7 km").replace(/[^\d.-]/g, '')));
The solution you can use is a Regular Expression, using the match function:
your_text = "11.7 km";
r = new RegExp("\\d|\\.","g");
matched_number = your_text.match(r);
number = matched_number.join("");
number_float = parseFloat(number)
This regular expression will match all numerical values in a string, regardless of text before or after the value.
var str = "11.7 km\n" +
"Text before 11.7 km\n" +
"11.7 km Text after\n" +
"Text before 11.7 km Text after\n";
var matches = str.match(/(\.\d*)*\d+(\.\d*)*/igm).map(parseFloat);
console.log('string "' + str + '" has ' + matches.length + " matches:");
console.log(matches);