0

I have string like

11.7 km

and I need get only int( 11.7 ), how can I do this with JavaScript?

Thanks.

7 Answers7

3

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".

ParseFloat reference

ParseInt reference

Jeroen
  • 147
  • 1
  • 12
2

You can use replace method by passing a regex expression as argument.

console.log('11.7 km'.replace(/[^0-9.]/g, ''));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

Try This.

var numbers = distance.replace(/[^0-9.]/g,'');
alert(numbers);
Siddharth Ramani
  • 661
  • 3
  • 12
0

You can use parseFloat('11.7km') this will return 11.7

Wanjia
  • 799
  • 5
  • 19
0

You can also use this.

console.log(Number(("11.7 km").replace(/[^\d.-]/g, '')));
Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
0

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)
0

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);
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28