I am trying to multiply each every index number together and seems like parseInt also return a decimal in the end...Not sure why?
var decNum = "12312312312312";
if( decNum.length == 14)
{
var lastnum = decNum.charAt(13);
var newNum = parseInt(decNum)/14; // rather 1231231231231 it shows 1231231231231.2 should be 13 nums left without last digit in int.
var validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
var sum;
for (var i = 0; i < validNum.length; i++) {
//since I can't use charAt for for INT so parse to string and parse it back to int to do the math.
sum += parseInt(validNum[i]) * parseInt(String(newNum.charAt(i)));
}
parseInt returns a number, so var newNum = parseInt(decNum)/14; results in newNum being a number, not a string. So, you can't use charAt on a number - you want the string. You have decimals because when you divide an integer (decNum) by 14, the result is a continuing decimal.
If you want to use explicit type conversions:
const newNum = String(parseInt(decNum / 14));
You don't need to parseInt the elements of validNum since they're already integers.
Your sum is not initialized to 0, so subsequent sum += lines will fail.
Even after fixing that, it would still be more elegant to use array methods to iterate over the string, though:
const decNum = "12312312312312";
if( decNum.length == 14) {
const newNum = String(parseInt(decNum / 14));
const validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
const charCodeArr = newNum.split('').map(char => char.charAt(0));
const sum = charCodeArr.reduce((sumSoFar, charCode, i) => {
return sumSoFar + (charCode * validNum[i]);
}, 0);
console.log(sum);
}
everything works fine now, thanks, everyone.
var decNum = "12312312312312";
if( decNum.length == 14)
{
var lastnum = decNum.charAt(13);
var newNum = String(parseInt(decNum)/14);
var validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
var sum = 0;
for (var i = 0; i < validNum.length; i++) {
sum += parseInt(validNum[i]) * parseInt(newNum.charAt(i));
}
Related
I have a function that I have modified to get a string (which consists of zeros and ones only).
The string (timesheetcoldata):
100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000
The string items (the numbers one and zero) will change every time the function is run.
It will always be the same length.
I have made the string above easier to see what I am trying to achieve.
I want to return the first character and then every 24th character (as in the variable colsCount in the function).
so, in the example above, it would return something like: 111111
I then want to convert these characters to numbers (something like [1, 1, 1, 1, 1, 1]).
I then want to sum these number together (so it would return, in the example: 6).
I then want to check if the returned number matches the variable: rowsCount
or true if it does, false if it does not.
My function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var colsCount = 24;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
console.log(timesheetcoldata);
});
Thank you very much to both Rajesh and MauriceNino (and all other contributers).
With their code I was able to come up with the following working function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
var count = 0;
var list = [];
for(var i = 0; i< timesheetcoldata.length; i+=24) {
const num1 = Number(timesheetcoldata.charAt(i));
list.push(num1);
count += num1;
}
let isSameAsRowsCount = count == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
});
You can always rely on traditional for for such action. Using functional operations can be more readable but will be more time consuming(though not by much).
You can try this simple algo:
Create a list that will hold all numbers and a count variable to hold sum.
Loop over string. As string is fixed, you can set the increment factor to the count(24).
Convert the character at given index and save it in a variable.
Push this variable in list and also compute sum at every interval.
At the end of this loop, you have both values.
var string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
var count = 0;
var list = [];
for(var i = 0; i< string.length; i+=24) {
const num1 = Number(string.charAt(i));
list.push(num1);
count += num1;
}
console.log(list, count)
Here is a step by step explanation, on what to do.
Use match() to get every nth char
Use map() to convert your array elements
Use reduce() to sum your array elements
Everything needed to say is included in code comments:
const testData = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
// Step 1) Create array of numbers from string
const dataArr = testData.match(/.{1,24}/g) // Split on every 24th char
.map(s => Number(s[0])) // Only take the first char as a Number
console.log(dataArr);
// Step 2) Sum array Numbers
let dataSum = dataArr.reduce((a, b) => a + b); // Add up all numbers
console.log(dataSum);
// Step 3) Compare your variables
let rowsCount = 123; // Your Test variable
let isSameAsRowsCount = dataSum == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
As #Jaromanda mentioned, you can use the following to done this.
const string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
const value = string.split('').filter((e,i)=> !(i%24)).reduce((acc,cur)=> acc+ (+cur), 0);
console.log(value);
I have a page with a grid where user's numbers get saved. It has a following pattern - every number ends with 3 digits after comma. It doesn't look nice, when for example user's input is
123,450
123,670
123,890
It's much better to have just 2 numbers after comma, because last 0 is absolutely meaningless and redundant.
The way it still should have 3 digits is only if at least one element in an array doesn't end up with 0
For example:
123,455
123,450
123,560
In this case 1st element of the array has the last digit not equal to 0 and hence all the elements should have 3 digits. The same story with 2 or 1 zeros
Zeros are redundant:
123,30
123,40
123,50
Zeros are necessary:
123,35
123,40
123,50
The question is how can I implement it programatically? I've started like this:
var zeros2Remove = 0;
numInArray.forEach(function(item, index, numInArray)
{
var threeDigitsAfterComma = item.substring(item.indexOf(',') + 1);
for(var j = 2; j <= 0; j--)
{
if(threeDigitsAfterComma[j] == 0)
{
zeros2Remove =+ 1;
}
else //have no idea what to do..
}
})
Well in my implementation I don't know how to do it since I have to iterate through every element but break it if at least 1 number has a last digit equal to zero.. In order to do that I have to break outer loop, but don't know how and I'm absolutely sure that I don't have to...
I think the following code what you are looking for exactly , please manipulate numbers and see the changes :
var arr = ["111.3030", "2232.0022", "3.001000", "4","558.0200","55.00003000000"];
var map = arr.map(function(a) {
if (a % 1 === 0) {
var res = "1";
} else {
var lastNumman = a.toString().split('').pop();
if (lastNumman == 0) {
var m = parseFloat(a);
var res = (m + "").split(".")[1].length;
} else {
var m = a.split(".")[1].length;
var res = m;
}
}
return res;
})
var maxNum = map.reduce(function(a, b) {
return Math.max(a, b);
});
arr.forEach(function(el) {
console.log(Number.parseFloat(el).toFixed(maxNum));
});
According to MDN,
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop or for...of instead.
If you convert your forEach loop to a for loop, you can break out of it with a label and break statement:
// unrelated example
let i;
let j;
outerLoop:
for (i = 2; i < 100; ++i) {
innerLoop:
for (j = 2; j < 100; ++j) {
// brute-force prime factorization
if (i * j === 2183) { break outerLoop; }
}
}
console.log(i, j);
I gave you an unrelated example because your problem doesn't need nested loops at all. You can find the number of trailing zeroes in a string with a regular expression:
function getTrailingZeroes (str) {
return str.match(/0{0,2}$/)[0].length;
}
str.match(/0{0,2}$/) finds between 0 and 2 zeroes at the end of str and returns them as a string in a one-element array. The length of that string is the number of characters you can remove from str. You can make one pass over your array of number-strings, breaking out when necessary, and use Array.map as a separate truncation loop:
function getShortenedNumbers (numInArray) {
let zeroesToRemove = Infinity;
for (const str of numInArray) {
let candidate = getTrailingZeroes(str);
zeroesToRemove = Math.min(zeroesToRemove, candidate);
if (zeroesToRemove === 0) break;
}
return numInArray.map(str => str.substring(0, str.length - zeroesToRemove);
}
All together:
function getTrailingZeroes (str) {
return str.match(/0{0,2}$/)[0].length;
}
function getShortenedNumbers (numInArray) {
let zeroesToRemove = Infinity;
for (const str of numInArray) {
let candidate = getTrailingZeroes(str);
zeroesToRemove = Math.min(zeroesToRemove, candidate);
if (zeroesToRemove === 0) break;
}
return numInArray.map(str => str.substring(0, str.length - zeroesToRemove));
}
console.log(getShortenedNumbers(['123,450', '123,670', '123,890']));
console.log(getShortenedNumbers(['123,455', '123,450', '123,560']));
This solution might seem a little cumbersome but it should work for all possible scenarios. It should be easy enough to make always return a minimal number of decimals places/leading zeros.
I hope it helps.
// Define any array
const firstArray = [
'123,4350',
'123,64470',
'123,8112390',
]
const oneOfOfYourArrays = [
'123,30',
'123,40',
'123,50',
]
// Converts 123,45 to 123.45
function stringNumberToFloat(stringNumber) {
return parseFloat(stringNumber.replace(',', '.'))
}
// For 123.45 you get 2
function getNumberOfDecimals(number) {
return number.split('.')[1].length;
}
// This is a hacky way how to remove traling zeros
function removeTralingZeros(stringNumber) {
return stringNumberToFloat(stringNumber).toString()
}
// Sorts numbers in array by number of their decimals
function byNumberOfValidDecimals(a, b) {
const decimalsA = getNumberOfDecimals(a)
const decimalsB = getNumberOfDecimals(b)
return decimalsB - decimalsA
}
// THIS IS THE FINAL SOLUTION
function normalizeDecimalPlaces(targetArray) {
const processedArray = targetArray
.map(removeTralingZeros) // We want to remove trailing zeros
.sort(byNumberOfValidDecimals) // Sort from highest to lowest by number of valid decimals
const maxNumberOfDecimals = processedArray[0].split('.')[1].length
return targetArray.map((stringNumber) => stringNumberToFloat(stringNumber).toFixed(maxNumberOfDecimals))
}
console.log('normalizedFirstArray', normalizeDecimalPlaces(firstArray))
console.log('normalizedOneOfOfYourArrays', normalizeDecimalPlaces(oneOfOfYourArrays))
Try this
function removeZeros(group) {
var maxLength = 0;
var newGroup = [];
for(var x in group) {
var str = group[x].toString().split('.')[1];
if(str.length > maxLength) maxLength = str.length;
}
for(var y in group) {
var str = group[y].toString();
var substr = str.split('.')[1];
if(substr.length < maxLength) {
for(var i = 0; i < (maxLength - substr.length); i++)
str += '0';
}
newGroup.push(str);
}
return newGroup;
}
Try it on jsfiddle: https://jsfiddle.net/32sdvzn1/1/
My script checks the length of every number decimal part, remember that JavaScript removes the last zeros in a decimal number, so 3.10 would be 3.1, so the length is less when there is a number with zeros in the end, in this case we just add a zero to the number.
Update
I've updated the script, the new version adds as much zeros as the different between the max decimal length and the decimal length of the analyzed number.
Example
We have: 3.11, 3.1423, 3.1
The max length would be: 4 (1423)
maxLenght (4) - length of .11 (2) = 2
We add 2 zeros to 3.11, that will become 3.1100
I think you can start out assuming you will remove two extra zeros, and loop through your array looking for digits in the last two places. With the commas, I'm assuming your numArray elements are strings, all starting with the same length.
var numArray = ['123,000', '456,100', '789,110'];
var removeTwo = true, removeOne = true;
for (var i = 0; i < numArray.length; i++) {
if (numArray[i][6] !== '0') { removeTwo = false; removeOne = false; }
if (numArray[i][5] !== '0') { removeTwo = false; }
}
// now loop to do the actual removal
for (var i = 0; i < numArray.length; i++) {
if (removeTwo) {
numArray[i] = numArray[i].substr(0, 5);
} else if (removeOne) {
numArray[i] = numArray[i].substr(0, 6);
}
}
I have a string like below, which i want to split using a number and "+", i tried with the below code,
Input String:
20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A
Code:
First found the len of the string,
var str1 = 20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A
str2 = str1.length;
if (str2 > '400') {
var str3 = str1.split("+", 100);
}else{
var str3 = str1
}
Desired Output:
str3[0] = 20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407
str3[1] = 20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085
str3[2] = 20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054
str3[3] = 20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345
str3[4] = 20346+20348+20349+20355+20356.A
Length by default here is 100 and which should decrease based on the string rather than increasing (help need to accomplish this)
Please help me on this with some guidance
Almost the same as Nina Scholz's answer, but a little different. Starts from 0 then looks for the "+" after the next 100 characters then copies that to the result array. Starts again from the character after the "+" until the string is exhausted.
var s = '20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A';
var start = 0,
min = 100,
pos = 0,
result = [];
while (pos != -1) {
pos = s.indexOf('+', start + min);
result.push(s.substring(start, pos == -1? s.length : pos));
start = pos+1;
}
console.log(result);
You could use String#indexOf with a right start value as fromIndex to search for the next + and slice the string for the parts.
var string = '20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A',
length = 100,
start = 0,
pos,
result = [];
while ((pos = string.indexOf('+', start + length)) !== -1) {
result.push(string.slice(start, pos));
start = pos + 1;
}
result.push(string.slice(start));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Is this what you are looking for explanation in comments
var s = "20001+20002+20003+20005+20019+20035+20009+20011+20015+20006+20020+20047+20048+20050+20049+204044+22407+20052+20057+20058+20059+20063+20065+20067+20068+20070+20072+20073+20075+20076+20078+20081+20084+20085+20086+20140+21954+206171+206170+206175+20093+206168+206177+206172+20098+206167+20107+20053+20054+20056+20108+20109+20110+20112+20115+20117+20119+20124+20126+20131+20132+20136+20141+20344+20345+20346+20348+20349+20355+20356.A"
var d = [];
var slug = 100;//threshold value for separatuion
var rounds = Math.ceil(s.length/slug); //find how many elemnts shall be formed
console.log(rounds);
for(var i=0;i<rounds;i++){ //loop it
d.push(s.substr(0,slug)); //extract the basic initial string
//console.log(d,s,s.length) //extract the remaining string for next iteration
s = (s.length > slug) ? s.substr(slug) : s //make sure for last string less than slug value
}
console.log(d,d.length);
How do I square a number's digits? e.g.:
square(21){};
should result in 41 instead of 441
This is easily done with simple math. No need for the overhead of string processing.
var result = [];
var n = 21;
while (n > 0) {
result.push(n%10 * n%10);
n = Math.floor(n/10);
}
document.body.textContent = result.reverse().join("");
In a loop, while your number is greater than 0, it...
gets the remainder of dividing the number by 10 using the % operator
squares it and adds it to an array.
reduces the original number by dividing it by 10, dropping truncating to the right of the decimal, and reassigning it.
Then at the end it reverses and joins the array into the result string (which you can convert to a number if you wish)
I think he means something like the following:
var output = "";
for(int i = 0; i<num.length; i++)
{
output.concat(Math.pow(num[i],2).toString());
}
I believe this is what the OP is looking for? The square of each digit?
var number = 12354987,
var temp = 0;
for (var i = 0, len = sNumber.length; i < len; i += 1) {
temp = String(number).charAt(i);
output.push(Number(temp) * Number(temp));
}
console.log(output);
Split the string into an array, return a map of the square of the element, and rejoin the resulting array back into a string.
function squareEachDigit(str) {
return str.split('').map(function (el) {
return (+el * +el);
}).join('');
}
squareEachDigit('99') // 8181
squareEachDigit('52') // 254
DEMO
function sq(n){
var nos = (n + '').split('');
var res="";
for(i in nos){
res+= parseInt(nos[i]) * parseInt(nos[i]);
}
return parseInt(res);
}
var result = sq(21);
alert(result)
You'll want to split the numbers into their place values, then square them, then concatenate them back together. Here's how I would do it:
function fn(num){
var strArr = num.toString().split('');
var result = '';
for(var i = 0; i < strArr.length; i++){
result += Math.pow(strArr[i], 2) + '';
}
return +result;
}
Use Math.pow to square numbers like this:
Math.pow(11,2); // returns 121
I have a number in JavaScript that I'd like to convert to a money format:
556633 -> £5566.33
How do I do this in JavaScript?
Try this:
var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"
This works:
var currencyString = "£" + (amount/100).toFixed(2);
Try
"£"+556633/100
This script making only integer to decimal.
Seperate the thousands
onclick='alert(MakeDecimal(123456789));'
function MakeDecimal(Number) {
Number = Number + "" // Convert Number to string if not
Number = Number.split('').reverse().join(''); //Reverse string
var Result = "";
for (i = 0; i <= Number.length; i += 3) {
Result = Result + Number.substring(i, i + 3) + ".";
}
Result = Result.split('').reverse().join(''); //Reverse again
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
return Result;
}
Using template literals you can achieve this:
const num = 556633;
const formattedNum = `${num/100}.00`;
console.log(formattedNum);