limit the query exactly with 8 and 7 digits in javascript - javascript

i have a little question:
how i can limit or generate the result of a query in 7 or 8 digits
example:
var x = 3143284294
var y = 387520525892
var z = -7632489234892
var w = 34563
result:
var x = 3143284
var y = 3875205
var z = -763248
var w = 3456300 (fill whit "0")
What function or prefix in javascript will use?
tnks(and sorry for my english)

This converts the number to a string and performs string operations on it. Note that repeat is a fairly recent feature of ECMAScript.
function cutNum(n, limit) {
n = n + '';
n = n.substr(0, limit);
if (n.length < limit) {
n = n + '0'.repeat(limit - n.length);
}
return parseInt(n, 10);
}
var x = 3143284294;
cutNum(x, 7); // 3143284
var z = -7632489234892;
cutNum(z, 7); // -763248
var w = 34563;
cutNum(w, 7); // 3456300

Take a look at the slice() method.
var numbers = "01234567890";
var res = numbers.slice(0,6);
alert(res);
Since your sample also includes that are less than 7 digits, you will want to run a logic check first prior to the slice.
var x = "01"
if(x.length < 7)
x = x + "0000000";
x = x.slice(0,6);
alert(x);

Related

Generate Reference Number to Google Sheets automatically using Google Apps Script

I am trying to generate a reference number every time a new data in inserted automatically from Google Form.
I would like to generate the format as TMS180001 until the maximum possible reference number which is TMS189999. I could not figure how to format the value/string to 0001 instead of 1 and when I ran below code nothing happened.
function onFormSubmit(e) {
var Time = e.values [0]; //column 1 timestamp
var TMSrefnum = [10]; //column 1 till 9 are other information while
//column 10 is the reference number
if (Time = true); //if timestamp has value then add reference
//number to column 11
var i = 1 ; i < 9999 ; i++;
TMSrefnum = "TMS18" + toString(i);
}
Zero Padding
For zero padding use your own functions e.g.
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
This will allow you to execute the .pad() method on any Number in your script.
Or write a method that looks something like this:
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
pad(98); // returns "000000098"
Sources:
https://stackoverflow.com/a/11187738/1139105
https://stackoverflow.com/a/2998822/1139105
See this answer to the question How to output integers with leading zeros in JavaScript.
You'll need to create an extra function outside the onFormSubmit() function (or include the Polyfill).
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Then you would call
TMSrefnum = "TMS18" + pad(currentEntryNumber, 4);
I managed to produce the reference number from below code.
var sheet1 = ss.getSheets()[0];
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
var valuerange = sheet1.getRange("A1:A").getValues();
var lastrownumber = valuerange.filter(String).length-1;
var TMSNUM = "TMS18" + pad(lastrownumber, 4);

Index of each CharAt and multiplying each index number

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

separating numbers into sum of positional digits in javascript

I'm working with freecodecamp studies and need to find a way to turn a number into sum of positional digits like [1234] to [1000,200,30,4].
Code looks like this:
for(var i=0;i<newArr.length;i++){
var order = newArr.length-1 - i;
newArr.splice(i,1,newArr[i]*1e(order));
}
Here newArr will be 1234.
Node gives error: invalid token 1e(order).
Need some advice how to make it right.
I think you can use the below logic
var n = 123456;
n=n.toString();
var arr = n.split("");
var b = arr.map(function(x,i) {
return x * Math.pow(10, (arr.length-i-1));;
});
console.log(b);
var a = 1234
b = []
while(a>0){
b.unshift(a%10 * (10 ** b.length))
a = parseInt(a/10)
}
console.log(b)
Number.prototype.padRight = function (n,str) {
return (this < 0 ? '-' : '') + (Math.abs(this)+ Array(n-String(Math.abs(this)).length+1).join(str||'0'));
}
var digits = "1234"
var tempCounter= digits.length;
var result=[];
for(var i=0;i<digits.length;i++,tempCounter--){
result.push(parseInt(digits[i]).padRight(tempCounter))
}
console.log(result);

Get id as a number in javascript..?

A simple question..
var x = document.getElementById('xNum');
var y = document.getElementById('xNum');
var result = x * y;
document.write(result);
and
<div id="xNum">20</div>
<div id="yNum">50</div>
It displays 20 and 50. why not calculating 20 * 50? Why does it get as a integer or how can I get numbers in an div?
Thanx!
I don't get any result with that:
var x = document.getElementById('xNum').innerHTML;
var y = document.getElementById('xNum').innerHTML;
var result = parseInt(x) * parseInt(y);
document.write(result);
Use parseInt and process it on their HTML,
var result = parseInt(x.innerHTML) * parseInt(y.innerHTML)
If you don't need to support browsers priot to IE9, you should use textContent instead of innerHTML.
If your numbers might be floats you should check out parseFloat instead
If you need to be able to handle numbers like 012 you should specify the radix parameter as they might be interpreted the wrong way by parseInt.
In this case you should use parseInt(x.innerHTML,10)
it should be
var x = document.getElementById('xNum').innerHTML;
var y = document.getElementById('yNum').innerHTML;
var result = x * y;
document.write(result);
Parse them into integers:
var x = document.getElementById('xNum');
var y = document.getElementById('yNum');
var result = parseInt(x.innerHTML, 10) * parseInt(y.innerHTML, 10);
The value you are getting is a string, so in order to use it as a number you should cast it to the integer (or float):
var x = +document.getElementById('xNum').innerHTML;
var y = +document.getElementById('xNum').innerHTML;
var result = x * y;
I used unary + operator, there are another methods like parseInt, Number constructor, etc.
By now the possible ways would have been exhausted, but here's an example with textContent:
var x = document.getElementById('xNum'),
y = document.getElementById('yNum'),
toIntNum = function(element) {
return parseInt(element.textContent || element.innerText || 0, 10);
},
result;
result = toIntNum(x) * toIntNum(y);
Demo
Js:
var x = document.getByElementId('xNum').innerHTML;
var y = document.getByElementId('xNum').innerHTML;
var result = parseInt(x) * parseInt(y);
document.write(result);
you must cast as int so calculation done. By default the value consider as string .
var x = document.getByElementId('xNum');
var y = document.getByElementId('xNum');
var result = parseInt(x) * parseInt(y); //use parseInt or parseDouble
document.write(result);
and
<div id="xNum">20</div>
<div id="yNum">50</div>
it give 1000
You have to use parseInt() function in javascript for parsing a string to return an integer.
Your code should be like this :
var x = document.getElementById('xNum');
var y = document.getElementById('yNum');
var result = parseInt(x.innerHTML) * parseInt(y.innerHTML);
document.write(result);

Adding commas, decimal to number output javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/
var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}
Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!
This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}
function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

Categories