How to convert string (number with prefix) to Double/Float in JS - javascript

How to convert a number with prefix into double/float e.g. STA01.02to 1.02?

Use regex to strip the non-numbers (excluding ".") for a more flexible solution:
parseFloat("STA01.02".replace(/[^0-9\.]+/g, ''));

// Assumed "STA0" is the fixed-length prefix, you can adjust the substring at the start you're getting rid of.
var myString = "STA01.02";
var noPrefix = myString.substring(4); // Just "1.02"
var myNumber = parseFloat(noPrefix);
console.log(myNumber); // Prints 1.02

If the prefix always the same...
var str = "STA01.02";
var number = parseFloat(str.substring(3));

Related

How to parse string value "(20)" to Integer in Javascript?

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

javascript parseInt to remove spaces from a string

I have an example of data that has spaces between the numbers, however I want to return the whole number without the spaces:
mynumber = parseInt("120 000", 10);
console.log(mynumber); // 120
i want it to return 120000. Could somebody help me with this?
thanks
update
the problem is I have declared my variable like this in the beginning of the code:
var mynumber = Number.MIN_SAFE_INTEGER;
apparently this is causing a problem with your solutions provided.
You can remove all of the spaces from a string with replace before processing it.
var input = '12 000';
// Replace all spaces with an empty string
var processed = input.replace(/ /g, '');
var output = parseInt(processed, 10);
console.log(output);
Remove all whitespaces inside string by a replace function.
using the + operator convert the string to number.
var mynumber = Number.MIN_SAFE_INTEGER;
mynumber = "120 000";
mynumber = mynumber.replace(" ", "");
console.log(+mynumber );
You can replace all white space with replace function
var mynumber = "120 000";
console.log(mynumber.replace(/ /g,''));
OutPut is 120000
Just like playing with javascript :-)
var number= '120 00';
var s= '';
number = parseInt(number.split(' ').join(s), 10);
alert(number);

Parsing a String looking characters

I am trying to extract the numbers of this string: "ax(341);ay(20);az(3131);"
I think that I can do it how this:
var ax = data.split('(');
var ax2 = ax[1].split(')');
ax2[0] has "341"
Now If I can repeat this but starting in the next indexOf to take the second number.
I think that it's a bad practice, so I ask you If you have a better idea.
Thanks in advance
Use a regular expression:
var str = "ax(-341);ay(20);az(3131);"
var regex = /(-?\d+)/g
var match = str.match(regex);
console.log(match); // ["-341", "20", "3131"]
Now you can just access the numbers in the array as normal.
DEMO
You can use regex to extract all numbers from this.
var data = "ax(341);ay(20);az(3131);";
var ax = data.match(/\d+/g);
Here ax is now ["341", "20", "3131"]
Note that ax contains numbers as string. To convert them to number, use following
ax2 = ax.map( function(x){ return parseInt(x); } )
EDIT: You can alternatively use Number as function to map in the line above. It'll look like,
ax2 = ax.map( Number )
After this ax2 contains all the integers in the original string.
You could use a regular expression, eg:
var string = 'ax(341);ay(20);az(3131);';
var pattern = /([0-9]{1,})/g;
var result = string.match(pattern);
console.log(result);
// ["341", "20", "3131"]
http://regex101.com/r/zE9pS7/1

javascript : parse float with string prefix in both start and end

how to convert this string to float?
i want result 900.50
case-1: var convertThis = 'any string here 900,50 also any string here';
case-2: var convertThis = 'any string here 900.50 also any string here';
How to do this?
Try following code:
var text = 'any string here 900,50 also any string here';
var matched = text.match(/\d+[,.]\d+/)[0].replace(',', '.');
var num = parseFloat(matched, 10);
console.log(matched);
console.log(num);
prints:
900.50
900.5
You could do this :
var num = parseFloat(convertThis.replace(/[^\d\.,]/g,'').replace(/,/,'.'));
But be aware that this would break as soon as you have more than one number or dot in your text. If you want something reliable, you need to be more precise about what the string can be.
Supposing you'd want to extract all numbers from a more complex strings, you could do
var numbers = convertThis.split(/\s/).map(function(s){
return parseFloat(s.replace(',','.'))
}).filter(function(v) { return v });
Here, you'd get [900.5]
var myFloat = +(convertThis.match(/\d+[,\.]?\d+/)[0].replace(",","."))

How to remove part of a string?

Let’s say I have test_23 and I want to remove test_.
How do I do that?
The prefix before _ can change.
My favourite way of doing this is "splitting and popping":
var str = "test_23";
alert(str.split("_").pop());
// -> 23
var str2 = "adifferenttest_153";
alert(str2.split("_").pop());
// -> 153
split() splits a string into an array of strings using a specified separator string.
pop() removes the last element from an array and returns that element.
If you want to remove part of string
let str = "try_me";
str.replace("try_", "");
// me
If you want to replace part of string
let str = "try_me";
str.replace("try_", "test_");
// test_me
Assuming your string always starts with 'test_':
var str = 'test_23';
alert(str.substring('test_'.length));
Easiest way I think is:
var s = yourString.replace(/.*_/g,"_");
string = "test_1234";
alert(string.substring(string.indexOf('_')+1));
It even works if the string has no underscore. Try it at http://jsbin.com/
let text = 'test_23';
console.log(text.substring(text.indexOf('_') + 1));
You can use the slice() string method to remove the begining and end of a string
const str = 'outMeNo';
const withoutFirstAndLast = str.slice(3, -2);
console.log(withoutFirstAndLast);// output--> 'Me'

Categories