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.
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);
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));
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.
Related
I'm working with a string "(20)". I need to convert it to an int. I read parseInt is a function which helps me to achieve that, but i don't know how.
Use string slicing and parseInt()
var str = "(20)"
str = str.slice(1, -1) // remove parenthesis
var integer = parseInt(str) // make it an integer
console.log(integer) // 20
One Line version
var integer = parseInt("(20)".slice(1, -1))
The slice method slices the string by the start and end index, start is 1, because that’s the (, end is -1, which means the last one - ), therefore the () will be stripped. Then parseInt() turns it into an integer.
Or use regex so it can work with other cases, credits to #adeithe
var integer = parseInt("(20)".match(/\d+/g))
It will match the digits and make it an integer
Read more:
slicing strings
regex
You can use regex to achieve this
var str = "(20)"
parseInt(str.match(/\d+/g).join())
Easy, use this
var number = parseInt((string).substr(2,3));
You need to extract that number first, you can use the match method and a regex \d wich means "digits". Then you can parse that number
let str = "(20)";
console.log(parseInt(str.match(/\d+/)));
Cleaner version of Hedy's
var str = "(20)";
var str_as_integer = parseInt(str.slice(1, -1))
I have string like "17,420 ฿". How to change this as integer value. I have done
var a = "17,420 ฿"
var b = a.split(' ')[0];
console.log(Number(b))
But I am getting NaN because of ,.
So i have done like below
var c = b.replace( /,/g, "" );
console.log(Number(c));
Now, I am getting 17420 as an integer.
But, is there any better method to do it.
You could start by stripping off anything that's NOT a number or a decimal point. string.replace and a bit of RegExp will help. Then use parseFloat or Number to convert that number-like string into a number. Don't convert to an integer (a decimal-less number), since you're dealing with what appears to be currency.
const num = parseFloat(str.replace(/[^0-9.]/g, ''))
But then at the end of the day, you should NOT be doing string-to-number conversion. Store the number as a number, then format it to a string for display, NOT the other way around.
You can easily remove all non-digits with a regex like so:
a.replace(/\D/g, '');
Then use parseInt to get integer value:
parseInt(b);
Combined:
var result = parseInt(a.replace(/\D/g, ''));
You can use parseInt after removing the comma
var a = "17,420 ฿"
console.log(parseInt(a.replace(",",""), 10))
o/p -> 17420
Number(a.replace(/[^0-9.]/g, ""))
This will replace all not numbers chars... is that helpful?
Split for the , and then join via . and then parse it as a float. Use .toFixed() to determine how many decimal places you wish to have.
console.log(
parseFloat("17,420 ฿".split(' ')[0].split(',').join('.')).toFixed(3)
);
As a function:
const convert = (str) => {
return parseFloat(str.split(' ')[0].split(',').join('.')).toFixed(3)
}
console.log(convert("17.1234 $"));
console.log(convert("17 $"));
console.log(convert("17,2345 $"));
Alternative:
const convert = (str) => {
let fixedTo = 0;
const temp = str.split(' ')[0].split(',');
if(temp.length > 1){
fixedTo = temp[1].length;
}
return parseFloat(temp.join('.')).toFixed(fixedTo)
}
console.log(convert("17,1234 $"));
console.log(convert("17,123 $"));
console.log(convert("17,1 $"));
console.log(convert("17 $"));
For example given a string "43.44", is there any way to convert it to a float without casting or using parseFloat?
You could use an implicid type casting with an unary plus +.
var string = "43.44",
number = +string;
console.log(number);
console.log(typeof number);
you can do
let str = '43.44'
let val = (1 * str);
console.log(val);
console.log(typeof val)
I have a string like 203.99000 but I want to be like this 203.99. I tried to put toFixed here but I am using string so it didn't work. How can I do this?
Method 1:
var str = "203.99000";
str = parseFloat(str).toFixed(2)
In this case I'm using .parseFloat() to convert the string to a float number, then use the .toFixed() function to truncate decimals.
Method 2: Using .substr() and .indexOf():
var str = "203.99000";
str = str.substr(0, str.indexOf(".") + 3)
Method 3: Using .replace():
var str = "203.99000";
str = str.replace(/\.([\d]{2})\d+$/, ".$1")
The most accurate way is the first, because if you use other methods, the string just is truncated.
I'm just starting javascript and jquery and now I'm stuck with this kind of problem:
var myCharacter = ('#myCharacter').css('top'); // gives 140px
var numberOnly = myCharacter.replace('px',''); // gives 140
var total = numberOnly + 20; // gives 14020 not 160
I just don't understand why this happens.
you need parseInt()
var total = parseInt(numberOnly) + 20;
because numberOnly is a string, not a number, so its adding a number to a string which results in that 14020 as a string
When you replace 'px' in '140px', you end up with a variable of string type. (javascript has types, but they are dynamic)
When you call '140'+20, the type is not converted automatically, because + is an operation that makes sense on strings: concatenation.
You should explicitly convert to a number, for example by using parseInt('140'), then the addition should work as expected.
As one of the operands in numberOnly + 20 is a string, the + operator does string concatenation, not addition.
Use the parseInt method to parse the string to a number, then you don't have to remove the px part either, as the parsing ends when it encounters non-numerical characters.
var myCharacter = parseInt(('#myCharacter').css('top'), 10);
var total = myCharacter + 20;
That's because numberOnly is a String you can cast to int by doing:
var total = +numberOnly + 20
var myCharacter = ('#myCharacter').css('top'); // gives 140px
var numberOnly = myCharacter.replace('px',''); // gives 140
var total = parseInt(numberOnly) + 20;
you are trying to add up with string so first convert it into integer,use parseInt() to do this:
var total = parseInt(numberOnly) + 20;//160
numberOnly is still of type string, i.e. it's a number of characters. Thus you currently conctenate string '140' with 20, which is implicitly converted to a string.
To fix this, convert numberOnly to an integer using [parseInt][1].