Split a string into two using Javascript - javascript

I have a string COR000001. I want to split it so that I get only the integer 1. If the String is like COR000555 I should get the integer 555. Thank you...

The easiest method to use is to get rid of the first three characters "COR", "MCR", "TCP", etc.. and then use parseInt with the appropriate parameters such as in the below.
var str = "COR000555";
var n = parseInt (str.substr (3), 10); // force parseInt to treat every
// given number as base10 (decimal)
console.log (n);
555
If the "key" in the beginning is not always limited to three characters you could use a regular-expression to get all the digits in the end of your string.
.. as in the below;
var n = parseInt (str.match (/\d+$/)[0], 10);

I had just seen some one answer this question and before i could up vote it was deleted, hence posting the solution on his behalf.
var str='COR000050ABC';
var variable=parseFloat(/[0-9]+/g.exec(str));
though there was a small modification, added parseFloat

Related

Javascript convert string to integer

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.
1,700.00 + 500.00
returns 1,700.00500.00
So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.
The most relevant pages I read to resolve this were this question and this page. However when I use
parseInt(string, radix)
it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).
var a="1,700.00";
var b=500.00;
parseInt(a, 10);
Basic Answer
The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:
var num = '1,700.00';
num = num.replace(/\,/g,'');
This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.
num = parseInt(num);
Do this for each of your string numbers before adding them and everything should work.
More information
How the replace works:
More information on replace at mdn:
`/` - start
`\,` - escaped comma
`/` - end
`g` - search globally
The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.
Regular Expressions
A great tool to test regular expressions: Rubular and more info about them at mdn
If you are looking for a good tutorial here is one.
ParseInt and Rounding, parseFloat
parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:
2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`
For more information on parseInt look at mdn.
parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by #fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.
Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace() to get rid of each appearance of ,.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment #Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by #EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike #EpiphanyMachine solution. So you will be your own judge.
try this :
parseFloat(a.replace(/,/g, ''));
it will work also on : 1,800,300.33
Example :
parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01
Javascript doesn't understand that comma. Remove it like this:
a.replace(',', '')
Once you've gotten rid of the comma, the string should be parsed with no problem.

Remove last digits from an int

Can't seem to find a good answer to this question. How do I remove the last 11 digits from an int?
The id could be one or more numbers in the beginning but there will always be 11 digits following the id. There will always be an id in the beginning. {id}{11 digits}.
var getId = function (digits) {
// Do some stuff and return id
}
getId(110000000001); // Should return 1
getId(1110000000001); // Should return 11
getId(2010000000001); // Should return 20
Divide by 1e11 and take the floor:
var stripped = Math.floor(id / 1e11);
This avoids conversion to/from a string representation.
Note that the nature of JavaScript numerics is such that your "raw" values (the values with the 11 useless digits) can't have more than 5 digits in addition to those 11 before you'll start running into precision problems. I guess if you never care about the low-order 11 digits that might not be a problem.
Try this:
var str = 1100000000011;
var res = str.toString().substr(0, str.toString().length - 11);
Demo
You can convert your number to string and delete tailing digits:
digits.toString().replace(/\d{11}$/, '')
By the way, you better don't use ints (or to be precise, Numbers) because if number is greater than 2147483648 (by absolute value), it'll be represented internally as double resulting in precision loss. If don't need tailing digits, then it's okay — use division approach suggested in other answers (this one could break because of scientific notation). But if you want to keep all the data, you should represent your numbers with strings.
You can use division and 10^11 to do so.
Edit: my bad
var getId = function (digits) {
var id = parseInt((digits/(1e11)),0);
}
You can convert the number to a string and slice the last 11 characters from the end
parseInt( digits.toString().slice(0, -11) );
Using .slice( 0 , [ negative_number ]); will slice x characters from the end of the string
More information on .slice() Here

Add comma separator to a value variable

I have read some thousand comma separator JavaScript question/answer but found it hard to apply it in practice. For example I have the variable
x = 10023871234981029898198264897123897.231241235
How will I separate it in thousands with commas? I want a function that not only works with that number of digits but more. Regardless of the number of digits the function I need has to separate the number in commas and leaving the digits after the decimal point as it is, Can anyone help? It has to work on number and turn it into string.
First of all, for such huge numbers you should use string format:
var x = "10023871234981029898198264897123897.231241235";
Otherwise, JavaScript will automatically convert it to exponential notation, i.e. 1.002387123498103e+34.
Then, according to the question about money formatting, you can use the following code:
x.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
It will result in: "10,023,871,234,981,029,898,198,264,897,123,897.231241235".

How to get numerical value from String containing digits and characters

Is there any built in method to get which can parse int from string ("23px")?
I know I can use substring and then parseInt but I want to know if there is any other way available to do this.
parseInt will grab the first set of contiguous numbers:
parseInt('23px');
returns 23.
If there is any chance there will be leading zeros, use a radix:
parseInt('23px', 10);
which is a good habit in general.
parseInt can do it. Just use:
var num = parseInt("23px", 10);
It will parse the integer part and ignore the rest.

Javascript .split() a string for each number of characters

I have a variable that holds a number
var simpleNumber = 012345678;
I want to .split() this number and create an array that would be of each 3 numbers
the array should look like this
[012, 345, 678]
var splitedArray = simpleNumber.toString().split(/*how do i split this?*/);
it is part of a getRGB("ffffff") function, so i cant know what will be passed in.
Thanks
You can try:
var splittedArray = "012345678".match(/.../g);
function tridigit(n) {
return n.toString().match(/.{1,3}/g);
}
Note that if you prefix a number with a zero, it will be interpreted in octal. Octal literals are officially deprecated, but are supported for the time being. In any case, numbers don't have leading zeros, so it won't appear when you convert the number to a string.
Testing on Safari and FF, numbers with a leading 0 and an 8 or 9 are interpreted in base 10, so octal conversion probably wouldn't be a problem with your specific example, but it would be a problem in the general case.
Try this
var num = 123456789+"";// converting the number into string
var x1=num[0]+num[1]+num[2];//storing the individual values
var y1=new Array(x1);// creating a first group out of the first 3 numbers
var x2=num[3]+num[4]+num[5];
var y2=new Array(x2);// creating a second group out of the next 3 numbers
var x3=num[6]+num[7]+num[8];
var y3=new Array(x3);// creating a third group out of the next 3 numbers
var result=y1.concat(y2,y3);// concat all the 3 array
document.write(result);you get the output in the form of array
document.write("<br/>");
document.write(result[0]);
document.write("<br/>");
document.write(result[1]);
document.write("<br/>");
document.write(result[2]);
check the below link for the working example http://jsfiddle.net/informativejavascript/c6gGF/4/

Categories

Resources