ALEXANDER RAMIREZ
ALEXANDER RAMIREZ

Reputation: 41

Casting an string to float javascript

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.

Upvotes: 1

Views: 332

Answers (3)

Pierre Capo
Pierre Capo

Reputation: 1053

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

Upvotes: 4

mplungjan
mplungjan

Reputation: 177685

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

Upvotes: 1

Zeeshan Tariq
Zeeshan Tariq

Reputation: 624

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.

Upvotes: 0

Related Questions