We help IT Professionals succeed at work.

# How to calculate distance in (km) is lower then given distance in string (km)

on
125 Views
HI

I want to calculate distance is within the range of 1.0 km.
Iam using google distanematrix to get the distance in km to the place, and its working fine.

function returns a string, witch looks like f.eks:
- "0.9 km"
- "6.9 km"

I want to calculate so that distance is within the range of 1.0 km and not higher, but lower is ok...
But some times i also get distance in meter when iam close to the place, f.eks:
"14 m"
"20 m"

So how can i calculate correct distance if i get distance in double string value or as an int value?

Here is my if statement where iam checking the returned distance in km is lower then "1.0 km"
``````var dist = str.split(" "); //Split so i can only get the value and not the string "km"
if (Math.round(dist * 100) <= Math.round('1.0' * 100)) {
}
else{
}
``````

iam not getting the correct result with the code above, any suggestion for how i can calculate the correct way will be really appriciated...

Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Distinguished Expert 2017

Commented:
``````//I use the parseFloat function to get a float number
var dist = parseFloat(str.split(" ")); //Split so i can only get the value and not the string "km"
if(dist<=1.0){
}else{
}
``````

Commented:
Thanks for the response...

but what about if i get distance in meters f.eks ("20 m") and not km (4.4) ?
CERTIFIED EXPERT
Distinguished Expert 2017
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
``````<script>
var dist = "43 m";

var result = dist.match(/^(\d+[\.]?[\d+]?)\s+(.*)\$/);
if (result) {
// convert to meters
var newdist = result * (result == 'km' ? 1000 : 1);
console.log(newdist);
}
</script>
``````