Javascript Sum Values - javascript

I need to sum several values in javascript. I've tried by using following code
var a = 2;
var b = 5;
c = a+b;
But, instead of calculating the values of a and b, the output (c) only combine those two values. So the output given is :
c = 25
I believe you guys can help me easily about this. Thx before. Regard Andha.

Make sure the values are numbers, otherwise they will concat instead of suming.
a = parseInt(a, 10); // a is now int

Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you're not saying:
var a = '2'; // or something similar
Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.
Or as pointed out in the comments the Number function would probably suit your purposes.

The author has probably put "simplified" code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using "Number()" solved the problem:
var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value);

This works fine:
var a = 2;
var b = 5;
var c = a + b; // c is now 7

The code you show will not work the way you describe. It will result in 7.
However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.
This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt() [docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter (radix) to ensure the casting from string to number uses the base you expect. (The lack of info on radix in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt().)
Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN() [docs].

Use parseInt():
var a=2;
var b=5;
c=parseInt(a)+parseInt(b);

-Is important to apply Number() to every value. The ideal way is:
var sum = 0
sum = Number('93') + Number('7') //result 100
-instead of this way (careful with this)
var sum = 0
sum = Number('97' + '3') //result 937
-and careful with this (as variable is going to assign string type by default)
var sum = 0
sum = Number('97') + '3' //result "973"

You can simply convert string to a number by adding + before it. For somebody can be more readable.
Example:
const a = "2";
const b = "5";
const c = +a + +b
or const c = (+a) + (+b) may be more readable.
That will first convert the string to a Number.

Related

How to Unify Kotlin and Long.js Division Results

I have an issue,
I have a number that I wish to divide by 49 as shown in the code below:
// in Javascript:
let referenceNumber= 3487039819743582477;
let division = referenceNumber /49;
//I am using https://github.com/dcodeIO/long.js
//Now when I do the following with the Long.js library:
let longValue = Long.fromValue(division); //Long.js gave me 71164077953950662 as the result
//Now, in Kotlin:
val longValue = division.toDouble().toLong(); //Kotlin gave me 71164077953950664 as result
// As you can see, there is a difference of 2 between the two programming languages.
Which is the correct value here and How do I rectify this? I want both languages to give me exact value all the time after division and conversion to long
Thank you.
The problem is that you are doing toDouble(), which adds imprecision.
println(3487039819743582477 / 49) prints 71164077953950662.
If you want to know about Double and imprecision, check out https://floating-point-gui.de/.

Better way to put numbers side by side. Javascript

I was wondering if there was a better approach to putting 2 numbers side by side without having to make them into a string.
For example:
if i have '2' and '3' and I wanted to '23' you would just concat them. But what if they were the number data type.
I was working with binaries and realized I don't actually know anyway to have
0101, and 1010 and put them together to create 01011010 without turning them into strings.
I know it's an odd question but I am just curious. Thanks again.
Here's a method of doing it without string concatenation:
var values = [2,3];//Also works with arbitrary length arrays, e.g. [1,2,3,4,5]
var result = 0;
for (var i = 0; i < values.length; ++i) {
var step = values[i] * (Math.pow(10, values.length - i) / 10);
result += step;
}
https://jsfiddle.net/ysd6exvw/
I've haven't benchmarked it for speed, and TBH I would suggest just using string concatenation instead of complicating the problem with this code.
EDIT:
Added a benchmark:
https://jsfiddle.net/4ap82rgq/
This shows that the string concatenation is fastest, although I did get one result where the above code was faster.

How to store big int value in javascript with standard libraray [duplicate]

I'm working on the Project Euler problems (currently question 13).
For this question I have to find the first 10 digits of the sum of 100 numbers all of a size similar to this:
91,942,213,363,574,161,572,522,430,563,301,811,072,406,154,908,250
I think I could use something like Java's BigInteger, but I started solving the problems in JavaScript (I'm trying to boost my js abilities for work), and I would like to continue using it, even to solve this problem.
I'd like to stick to pure JS if possible.
Javascript recently got a new primitive data type BigInt (stage 4 proposal as of January 2020).
https://github.com/tc39/proposal-bigint
Chrome, Firefox and few other browsers have started supporting this in newer versions (check compatibility here), while other browsers are still implementing it.
https://developers.google.com/web/updates/2018/05/bigint
Basically it can be declared using either literals like
var a = 1n;
or
var b = BigInt('22222222222222222222222222222222');
Math operators don't do auto conversion between BigInt and Number, so
1 + 1n
will throw an error.
You are going to need a javascript based BigInteger library. There are many to choose from. Here is one https://github.com/peterolson/BigInteger.js
You can use it like this
var n = bigInt("91942213363574161572522430563301811072406154908250")
.plus("91942213363574161572522430563301811072406154908250");
Surprisingly, sticking all the values in an array and adding them all together and just taking the first 10 digits worked. I must have had a typo somewhere in my code when it didn't work before.
I'm sure that doing something this simple wouldn't work in all cases (like those #AlexMcmillan and #zerkms have been debating about). I think the safest bet is the BigInteger library mentioned by #bhspencer, but it seems like adding the first x significant digits with y digits as a buffer might also be worth a shot in some cases.
I did this using an array and updating all entries with a function.
function f(a) {
for (let i = 0; i < a.length - 1; i++) {
a[i + 1] = a[i + 1] + parseInt(a[i] / 10);
a[i] = a[i] % 10;
}
return a;
}
// remember to init the array with enough elements for all digits
var a = Array(200);
a.fill(0);
a[0] = 1;
Here is a JSFiddle with the code for problem 20.
You could always convert your sum to a string, rip out the . and grab the result - something like this:
var sum = 2384762348723648237462348;
sum = sum.toString(); // "2.3847623487236483e+24"
// Rip out the "."
sum = sum.substr(0, 1) + sum.substr(2);
// Grab the first 10 characters
var firstTen = sum.substr(0, 10);

Extremely large numbers in javascript

I'm working on the Project Euler problems (currently question 13).
For this question I have to find the first 10 digits of the sum of 100 numbers all of a size similar to this:
91,942,213,363,574,161,572,522,430,563,301,811,072,406,154,908,250
I think I could use something like Java's BigInteger, but I started solving the problems in JavaScript (I'm trying to boost my js abilities for work), and I would like to continue using it, even to solve this problem.
I'd like to stick to pure JS if possible.
Javascript recently got a new primitive data type BigInt (stage 4 proposal as of January 2020).
https://github.com/tc39/proposal-bigint
Chrome, Firefox and few other browsers have started supporting this in newer versions (check compatibility here), while other browsers are still implementing it.
https://developers.google.com/web/updates/2018/05/bigint
Basically it can be declared using either literals like
var a = 1n;
or
var b = BigInt('22222222222222222222222222222222');
Math operators don't do auto conversion between BigInt and Number, so
1 + 1n
will throw an error.
You are going to need a javascript based BigInteger library. There are many to choose from. Here is one https://github.com/peterolson/BigInteger.js
You can use it like this
var n = bigInt("91942213363574161572522430563301811072406154908250")
.plus("91942213363574161572522430563301811072406154908250");
Surprisingly, sticking all the values in an array and adding them all together and just taking the first 10 digits worked. I must have had a typo somewhere in my code when it didn't work before.
I'm sure that doing something this simple wouldn't work in all cases (like those #AlexMcmillan and #zerkms have been debating about). I think the safest bet is the BigInteger library mentioned by #bhspencer, but it seems like adding the first x significant digits with y digits as a buffer might also be worth a shot in some cases.
I did this using an array and updating all entries with a function.
function f(a) {
for (let i = 0; i < a.length - 1; i++) {
a[i + 1] = a[i + 1] + parseInt(a[i] / 10);
a[i] = a[i] % 10;
}
return a;
}
// remember to init the array with enough elements for all digits
var a = Array(200);
a.fill(0);
a[0] = 1;
Here is a JSFiddle with the code for problem 20.
You could always convert your sum to a string, rip out the . and grab the result - something like this:
var sum = 2384762348723648237462348;
sum = sum.toString(); // "2.3847623487236483e+24"
// Rip out the "."
sum = sum.substr(0, 1) + sum.substr(2);
// Grab the first 10 characters
var firstTen = sum.substr(0, 10);

Wrong type of variable

I have a simple javascript/jquery function that looks like this:
$("#add_a, #add_b").on("change keyup paste", function () {
var add_a = $('#add_a').val(),
add_b = $('#add_b').val(),
add = add_a + add_b;
$("#add").text(add);
});
The problem is that it treats the variables add_a and add_b as strings even though i get the value from a input with type="number". I have made other similar functions and haven't had this problem before!
To making it clear, if I type in 3 in #add_a and 4 in #add_b the result is 34 and not 7.
Is there a way to make sure it get the values as numbers or change it after?
Thanks in advance!
As you say, values from <input>s are treated as strings. You need to parse them as a number, for that, you can use parseInt:
var add_a = parseInt($('#add_a').val(), 10),
add_b = parseInt($('#add_b').val(), 10)
If you're expecting non-integer input, you can use parseFloat instead.
You can take a look here and parse the value as an Integer. If an Integer is what you want...

Categories

Resources