How to increment a numeric string by +1 with Javascript/jQuery - javascript

I have the following variable:
pageID = 7
I'd like to increment this number on a link:
$('#arrowRight').attr('href', 'page.html?='+pageID);
So this outputs 7, I'd like to append the link to say 8. But if I add +1:
$('#arrowRight').attr('href', 'page.html?='+pageID+1);
I get the following output: 1.html?=71 instead of 8.
How can I increment this number to be pageID+1?

Try this:
parseInt(pageID, 10) + 1
Accordint to your code:
$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));

+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.
$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));

All these solutions assume that your number you want to add 1 to is within the machine precision for an integer. So if you have a large enough number within that string when you add 1 to it won't change the number.
For Example:
parseInt('800000000000000000', 10) + 1 = 800000000000000000
So I wrote a quick solution to the problem
function addOne(s) {
let newNumber = '';
let continueAdding = true;
for (let i = s.length - 1; i>= 0; i--) {
if (continueAdding) {
let num = parseInt(s[i], 10) + 1;
if (num < 10) {
newNumber += num;
continueAdding = false;
} else {
newNumber += '0';
}
} else {
newNumber +=s[i];
}
}
return newNumber.split("").reverse().join("");
}
Now, using the same example above
addOne('800000000000000000') + 1 = '800000000000000001'
Note that it must stay as a string or you will lose that 1 at the end.

It needs to be a integer, not a string. Try this:
pageID = parseInt(pageID)+1;
Then you can do
$('#arrowRight').attr('href', 'page.html?='+pageID);

Simply, $('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The parentheses makes the calculation done first before string concatenation.

let pageId = '7'
pageId++
console.log(pageId)
Nowadays, you just need to pageID++.

Just change your order of operations by wrapping your addition in parentheses; if pageID is already a number, parseInt() isn't necessary:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
Demo

As long as your pageID is numeric, this should be sufficient:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The problem you were seeing is that JavaScript normally executes in left-to-right order, so the string on the left causes the + to be seen as a concatenator, so it adds the 7 to the string, and then adds 1 to the string including 7.

Related

Sum Strings as Numbers

I am trying to solve a kata that seems to be simple on codewars but i seem to not be getting it right.
The instruction for this is as simple as below
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
sumStrings('1','2') // => '3'
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
And this is what i have tried
function sumStrings(a,b) {
return ((+a) + (+b)).toString();
}
But the results solves all except two and these are the errors i get
sumStrings('712569312664357328695151392', '8100824045303269669937') - Expected: '712577413488402631964821329', instead got: '7.125774134884027e+26'
sumStrings('50095301248058391139327916261', '81055900096023504197206408605') - Expected: '131151201344081895336534324866', instead got: '1.3115120134408189e+29'
I don't seem to understand where the issues is from. Any help would help thanks.
The value you entered is bigger than the int type max value. You can try changing your code to:
function sumStrings(a,b) {
return ((BigInt(a)) + BigInt(b)).toString();
}
This way it should return the right value
You could pop the digits and collect with a carry over for the next digit.
function add(a, b) {
var aa = Array.from(a, Number),
bb = Array.from(b, Number),
result = [],
carry = 0,
i = Math.max(a.length, b.length);
while (i--) {
carry += (aa.pop() || 0) + (bb.pop() || 0);
result.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
while (carry) {
result.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
return result.join('');
}
console.log(add('712569312664357328695151392', '8100824045303269669937'));
console.log(add('50095301248058391139327916261', '81055900096023504197206408605'));
The problem is that regular javascript integers are not having enough space to store that much big number, So it uses the exponential notation to not lose its precision
what you can do is split each number into parts and add them separately,
one such example is here SO answer
My solution is:
function sumStrings(a,b) {
return BigInt(a) + BigInt(b) + ''
}
Converting from a string to a number or vice versa is not perfect in any language, they will be off by some digits. This doesn't seem to affect small numbers, but it affects big numbers a lot.
The function could go like this.
function sumStrings(a, b) {
return (BigInt(a) + BigInt(b)).toString() // or parseInt for both
}
However, it's still not perfect since if we try to do:
console.log((4213213124214211215421314213.0 + 124214321214213434213124211.0) === sumStrings('4213213124214211215421314213', '124214321214213434213124211'))
The output would be false.

String of numbers can't start with zero. Other Solutions? [duplicate]

This question already has answers here:
Remove leading zeros from a number in Javascript [duplicate]
(3 answers)
Closed 5 years ago.
I have a string that only contains numbers, but the string can not start with a zero.
The first thing I cam up with was this:
let myNumber = "0052";
myNumber = myNumber.split('');
for (let i = 0; i < myNumber.length; i++) {
if (myNumber[i] == '0') {
myNumber.splice(i, 1);
i--;
} else {
break;
}
}
console.log(myNumber);
console.log('result:', myNumber.join(''));
Everything works fine like that.
I thought there might be an other way without using a classical for-loop.
My attempt with a for-of loop failed. As soon as I remove the first entry of my array, the index of the loop does not reset, so it skips the second zero in my array. Here is the code for that:
let myNumber = "0052";
myNumber = myNumber.split('');
for (let n of myNumber) {
if (n == '0') {
myNumber.shift();
} else {
break;
}
}
console.log(myNumber);
console.log('result:', myNumber.join(''));
What other solutions to this problem are there? Is there a more performant solution?
What you're probably looking for is parseInt function.
const result = parseInt("0052", 10).toString();
console.log(result);
I also added toString() to convert number to a string. parseInt also accepts second argument - the radix. Read more about parseInt
Regexp: /^[0]+/
let myNumber = "0000000520";
console.log(myNumber.replace(/^[0]+/, ''))
Use
parseInt('0052') = 52
or
parseFloat('0052.29') = 52.29 if your number is float type:
I just have different and simpler approach than yours :)
while(myNumber.length){
if(myNumber.charAt(0) == '0')
myNumber = myNumber.substring(1, myNumber.length);
}
DEMO : https://jsbin.com/falejuruwu/1/edit?js,console

Show numbers to second nearest decimal

I'm very new to Javascript so please bear with me.
I have this function that adds up a total. How do I make it so that it shows the nearest two decimal places instead of no decimal places?
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function() {
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
}
Thank you!
Edit: As requested: commaFormatted:
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = "$" + minus + n;
return amount;
}
Well parseInt parses integers, so you are getting rid of any decimals right there. Use parseFloat.
E.g.
parseFloat('10.599').toFixed(2); //10.60
You might also want to change your commaFormatted function to something like:
function commaFormatted(amount) {
if (!isFinite(amount) || typeof amount !== 'number') return '';
return '$' + amount.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
}
commaFormatted(0); //$0.00
commaFormatted(1.59); //$1.59
commaFormatted(999999999.99); //$999,999,999.99
Use to function toFixed(2)
The 2 is an integer parameter that says use 2 decimal points, assuming your comma formatted code does not turn it into a string. (If it does, fix the decimals BEFORE you run it through the formatting)
$("#product-subtotal").val(CommaFormatted(parseFloat(prodSubTotal).toFixed(2)));
Remember to parseFloat because the val() could be a string!`
You're looking for toFixed(). It takes one parameter, digits. The parameter is documented as follows:
The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
Do also note that parseInt() parses integers, truncating any decimals you might have. parseFloat() will preserve decimals as expected.
I solved my problem. I simply changed:
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
to
$("#product-subtotal").val(prodSubTotal);
As I stated in the comments, this was not a script I wrote. It is a script Chris Coyier wrote and I was just trying to amend it. I guess I didn't need to use CommaFormatted for my purposes?
Thank you all for your help!

jQuery: why is an integer being added to a variable like a string?

So I'm trying to take the variable that increments in a for statement, and add an integer to it... but for some reason, it's adding the integer as though it were a string; other operations like subtraction or multiplication work as expected.
Why is this happening? Edit: I've added the whole function; the problem in question is where I try to add 2 to the variable x.
What confuses me is that I'm able to use x no problem, in an .eq() object for example...
$(function() {
$('textarea').bind('paste', function (e){
inputGroup = $(this).parent();
var ob = $(this);
if (e.type == 'paste'){
setTimeout(function(){
var data = ob.val();
var tabbed = data.replace(/\n/g, "\t");
var cells = tabbed.split("\t");
for(var x in cells) {
foo = x + 2;
alert(foo);
$(inputGroup).find('input').eq(x).val(cells[x]);
}
}, 1);
}
});
});
Why is this happening?
Because x is a string that just looks like a number. Cast to Number first and you'll get the result you expect:
"1" + 2 = "12"
Number("1") + 2 = 3
EDIT : Now that I see you are using split to turn a string into an array, your problem is definitely that you are concatenating strings. Cast to Number first, and your problem is solved.
Yes other arithmetic operations will work, since they will implicitly cast the operands to Numbers. Confusingly, "2" * 3 will in fact evaluate to the integer 6. Welcome to Javascript.
-tjw
Without more code, specifically the initialization of cells, I can't tell you the exact reason. But you can simply call parseInt() on x to turn it into an integer for addition
for(var x in cells) {
foo = parseInt(x, 10) + 2;
$(inputGroup).find('input').eq(foo).val(cells[x]);
}
Because + is a String concatenation but there is no equivalent String method for * or / so when using those it cast the value as a Number. Just cast x as an integer:
for(var x in cells) {
foo = parseInt(x, 10) + 2;
$(inputGroup).find('input').eq(foo).val(cells[x]);
}
The 10 in parseInt is saying to use a base 10 number system (as opposed to hex 16, e.g.).
As others have mentioned, x is a string. That's why.
There's a nice trick for casting strings as numbers in JavaScript that hasn't been mentioned though:
for(var x in cells) {
// Without the "var" here, you're setting a global
// variable during each loop iteration.
var foo = +x + 2;
$(inputGroup).find('input').eq(foo).val(cells[x]);
}

How can I change an HTML input value's data type to integer?

I'm using jQuery to retrieve a value submitted by an input button. The value is supposed to be an integer. I want to increment it by one and display it.
// Getting immediate Voting Count down button id
var countUp = $(this).closest('li').find('div > input.green').attr('id');
var count = $("#"+countUp).val() + 1;
alert (count);
The above code gives me a concatenated string. Say for instance the value is 3. I want to get 4 as the output, but the code produces 31.
How can I change an HTML input value's data type to integer?
To convert strValue into an integer, either use:
parseInt(strValue, 10);
or the unary + operator.
+strValue
Note the radix parameter to parseInt because a leading 0 would cause parseInt to assume that the input was in octal, and an input of 010 would give the value of 8 instead of 10
parseInt( $("#"+countUp).val() , 10 )
Use parseInt as in: var count = parseInt($("#"+countUp).val(), 10) + 1; or the + operator as in var count = +$("#"+countUp).val() + 1;
There is a parseInt method for that or Number constructor.
var count = parseInt(countUp, 10) + 1;
See w3schools webpage for parseInt.

Categories

Resources