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

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/

Related

parseInt fixing the value

Here I have a value with commas.
Ex:-var abc = "10,10.12";
If I use var x = parseInt(abc);
it is returning 10
Expected output is 10,10.12
as I have used ng-value="UpdatedPropuesta.VALOR_CUOTA | number:2" in JSP.
If you want an array of numbers out of the string then try this,
const input = "10,10.12";
var output = input.split(",");
output = output.map(i => Number(i));
console.log(output);
10,10.12
That is not the number 1010.12, it is the number 10, a comma operator, and the number 10.12.
Commas are not part of the JavaScript literal syntax.
However, in your case you're passing two arguments to parseInt, the first should be a string to convert (but JS will convert it to a strign) and the second is the radix – the number base – which should be an integer.
So JS's type conversion will lead to:
var x = parseInt('10', 10);
Which is of course 10.
After question update
var x = parseInt("10,10.12");
As comma are not part of JS numeric literals, the parse will stop at the comma because it is not a character that can appear in a number.
So the answer is still 10.

Getting specific digits in a binary number in javascript

I need to be able to take the first 8 digits in a binary number, and save that value to a variable, then save the next 8, and so on. I read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators on bitwise operations, but didn't see anything about getting a specific digit or set of digits. I suppose I could just AND the number in question with another number that is all zeros except for the digits in question, which would be ones. For instance if the number in question was 10110011010111, and I wanted the first 5 digits, I could do 1000110011010111 & 0000000000011111 which would return 0000000000010111, which would be fine, but if there's a better or more direct way to do this, I would prefer that.
Edit: I'm doing this to be able to store a number as a number in base 256, so I can use color to encode information. I don't need to know the actual ones and zeros in those locations, but what number they would be taken in groups of 8, and saving that number.
You could use splice:
var str = '10110011010111';
var arr = str.split('');
console.log(arr.splice(arr.length - 5, 5).join('')); // prints 10111

Converting Strings to Integer and get the persentage of two number

What I'm trying to do is to make a progress bar for donation. My html structure is:
<div class="hgoal" style="text-align: center;">My goal is to raise $<span id="mygoal">9,999.00</span></div>
<div class="donation-total">Total Donation<span id="total-donation">1,000.00</span></div>
my javascript so far is to get the innerHTML value of mygoal and total-donation.
var mygoal = document.getElementById("mygoal").innerHTML;
var totalgoal = document.getElementById("total-donation").innerHTML;
and I'm getting this as a result:
mygoal = "9,999.00";
total-donation = "1,000.00";
I believe this is a string and not an integer, and using parseInt() only give me the first digit number.
Can anyone give me an idea how can I make this into an integer that can use for computation? example:
mygoal + total-donation = 10,999.00
And also, any idea how can i get the percentage of this two varible?
Use .replace(/,/g,'') to replace commas, then you get the magic of type coercion to convert your string to a number during calculation...
var mygoal = document.getElementById("mygoal").innerHTML.replace(/,/g,'');
var totalgoal = document.getElementById("total-donation").innerHTML.replace(/,/g,'');
If you use + on strings, they will be appended to each other, but other mathematical operators (*/- etc...) will first coerce the strings into numbers. To force coercion, you can multiply by 1, or perhaps use Number("123123.123")...
Number(mygoal) + Number(totalgoal); // using addition, so coerce strings to numbers
(mygoal / total_donation) * 100; // does not need coercion
Your main issue is, that your numbers include colons. The parseFloat() call will work, once you replace these colons. You may use the following code to do so:
// define regexp to replace colons
var replaceColons = new RegExp(',', 'g');
// apply regex
num = num.replace(replaceColons, '');
mygoal=parseInt(mygoal.replace(/,/gi,"")) will give you mygoal=9999.
You should use parseFloat(), not parseInt() ...
More, you have to remove the commas from the string, since parseFloat() does not undertsand number formatting characters (like comma). So, for example:
mygoal = mygoal.replace(/,/g, '');
total_donation = total_donation.replace(/,/g, '');
To get the percentage of two numbers, use:
(mygoal / total_donation) * 100;
Note that in JavaScript you can't use 'minus' char (-) in variables names.
You could use for example 'underscore' char (_), or CamelCase, wich is the recommended style for variables in JavaScript.
You need to convert those Indian (maybe) numbers to valid Javascript numbers for the sum, then convert the output back to the initial format using Number.toLocaleString.
var mygoal = "9,999.00";
var total_donation = "1,000.00";
var total = Number((Number(mygoal.replace(/,/g, '')) + Number(total_donation.replace(/,/g, ''))).toFixed(2));
var finalResult = total.toLocaleString('en-IN',{minimumFractionDigits: 2 });
alert(finalResult);

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

Split a string into two using 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

Categories

Resources