1

I have an string defining the lattitude of an event with this format "p002.155" and "n003.196" being "p" and "n" the form the system define if the number is positive or negative.

I need to parse the string to float, tried with parseFloat but keeps getting NaN value because of the char inside the string

how can I do it?? Thanks.

1
  • 3
    Welcome to Stack Overflow! Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output. Commented Jul 26, 2018 at 12:01

3 Answers 3

4

You can replace the char and then convert to float:

var str = "n002.155";
str = +str.replace("p","").replace("n","-"); //here the leading `+` is casting to number
console.log(str);

Sign up to request clarification or add additional context in comments.

1 Comment

@ALEXANDERRAMIREZ if you don't mind, if it's working for you, check this answer as accepted please
1

You can use substring and look at the first char

function getFloat(str) {
  var sign = str.charAt(0)=="n"?-1:1;
  return parseFloat(str.substring(1))*sign;
}

var latPStr = "p002.155", latNStr = "n003.196";
console.log(getFloat(latPStr),getFloat(latNStr));

1 Comment

I often get downvotes when I post working solutions in js - not sure why but js users really don't like working answers, unless it was the first to be upvoted
0

You can convert a string to float like this:

var str = '3.8';
var fl= +(str);  //fl is a variable converted to float
console.log( +(str) );
console.log("TYPE OF FL IS THIS "+typeof fl);

+(string) will cast string into float.

2 Comments

Reading the question is always useful. How does this convert a string like "n003.196" to a float?
Why is this voted up at all? there is no handling of n/p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.