how do I add two variables by javascript [duplicate] - javascript

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 3 years ago.
the code below concatenates the two variables instead of adding them to get one value. any help on how to correct this?
<script type="text/javascript">
function calculatetotal1() {
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}

You can use Number() to convert values to number
function calculatetotal1() {
var mal = Number(document.getElementById('<%=txtadults.ClientID%>').value);
var child = Number(document.getElementById('<%=txtnumchilderen.ClientID%>').value);
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}

Parsing both variables as float should to the trick.
<script type="text/javascript">
function calculatetotal1() {
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = parseFloat(mal) + parseFloat(child);
document.getElementById('<%=txttotal.ClientID%>').value = res;
}

You need to convert those values to number before adding them using the + operator. There are several ways of doing that, but you can use parseInt or parseFloat for this:
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = parseFloat(mal) + parseFloat(child);
document.getElementById('<%=txttotal.ClientID%>').value = res;

You are getting input values from textbox and the datatype of textbox value by default is string. So your current code is just considering it as string and doing concatenation.
Try using parseFloat() function for both values.
Try the following code.
function calculatetotal1() {
var mal = parseFloat (document.getElementById('<%=txtadults.ClientID%>').value);
var child = parseFloat (document.getElementById('<%=txtnumchilderen.ClientID%>').value);
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}

In JavaScript, + operator acts like concatenation and add the values
Like below
Var x = 2 + 3 // will be 5
Var y = '2' + 3 // will be 23 as string

Related

Set the last number in a string to negative

I have a string with diffrent mathematical characters, and i want to make the last number negative/positive. Let's say the string is "100/5*30-60+333". The result i want is "100/5*30-60+(-333)", and i want to convert it back to positive ("100/5*30-60+333").
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n.split('+');
n.split('-');
n.split('*');
n.split('/');
console.log(n);
}
What i get is the whole hiddenText.value, and not an array of all numbers. Any tips?
First, I'd match all of the basic math operators to get their order:
const operatorsArr = n.match(/\+|\-|\/|\*/g)
Then, split the string:
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n = n.replace(/\+|\-|\/|\*/g, '|');
n = n.split('|');
console.log(n);
}
Then, you will have an array of numbers, in which you can mutate the last number easily:
n[n.lengh-1] *= -1;
Now we can combine the two arrays together:
let newArr;
for (let i = 0; i < n.length; i++) {
newArr.push(n[i]);
if (operatorsArr[i]) newArr.push(operatorsArr[i]);
}
At last, you can rejoin the array to create the new String with a seperator of your choosing. In this example I'm using a space:
newArr = newArr.join(' ')
Please let me know how that works out for you.
Let's say the string is "100/5*30-60+333". The result i want is
"100/5*30-60+(-333)", and i want to convert it back to positive
("100/5*30-60+333").
The following code does that:
let mathStr = '100/5*30-60+333';
console.log(mathStr);
let tokens = mathStr.split('+');
let index = tokens.length - 1;
let lastToken = tokens[index];
lastToken = '('.concat('-', lastToken, ')');
let newMathStr = tokens[0].concat('+', lastToken);
console.log(newMathStr); // 100/5*30-60+(-333)
console.log(mathStr); // 100/5*30-60+333
EDIT:
... and i want to convert it back to positive ("100/5*30-60+333").
One way is to declare mathStr (with the value "100/5*30-60+333") as a var at the beginning and reuse it, later as you need. Another way is to code as follows:
let str = "100/5*30-60+(-333)";
str = str.replace('(-', '').replace(')', '');
console.log(str); // 100/5*30-60+333
To get numbers You can use replace function and split check code bellow :
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = "100/5*30-60+333";
n = n.replace('+','|+');
n = n.replace('-','|-');
n = n.replace('*','|*');
n = n.replace('/','|/');
n=n.split('|');console.log(n);
// to use any caracter from array use it in removeop like example
// if we have array (split return) have 100 5 30 60 333 we get 100 for example
// we need to make removeop(n[0]) and that reutrn 100;
// ok now to replace last value to negative in string you can just make
// var lastv=n[n.length-1];
// n[n.length-1] ='(-'+n[n.length-1])+')';
//var newstring=n.join('');
//n[n.length-1]=lastv;
//var oldstring=n.join('');
}
function removeop(stringop)
{
stringop = stringop.replace('+','');
stringop = stringop.replace('-','');
stringop = stringop.replace('*','');
stringop = stringop.replace('/','');
return stringop;
}
If you really need to add "()", then you can modify accordingly
<script>
function myConversion(){
var str = "100/5*30-60-333";
var p = str.lastIndexOf("+");
if(p>-1)
{
str = str.replaceAt(p,"-");
}
else
{
var n = str.lastIndexOf("-");
if(n>-1)
str = str.replaceAt(n,"+");
}
console.log(str);
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
</script>

Get max value of similar items in array with Javascript

I have an array like this:
["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"]
and I want to get a final array that will group similar values that changes from each other only by the last numbers of the string ("13rq8", "13rq6", "13rq4", "13rq2", "13rq12", "13rq10"), and return only the biggest values like the example below:
["13dl", "12dl", "13rq12"]
Can you help me please resolve this in Javascript?
Thank You!
Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:
var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};
l.forEach(function(x) {
var m = x.match(/^(.*?)(\d*)$/);
var tag = m[1];
var num = parseInt("0" + m[2]);
if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});
var l2 = [];
for (var tag in tagNum) {
var num = tagNum[tag];
if (num) l2.push(tag + num);
else l2.push(tag);
}
console.log(l2);

How can I prefix and zeropad a number? [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 8 years ago.
I want a pattern like this:- GT-000001. This pattern gets incremented when a new record is inserted.
So I get values from my DB like this:
var pattern = 'GT-';
var init = 00000;
var recordnumber = 1; // This value i get dynamically.
var result = pattern + init + recodnumber;
But I get result = GT-01. I want result to be GT-000001. How to get this result?
The below example works for recordnumber upto 6 digits. outputing 'GT-000001', 'GT-000012', or 'GT-123456' based on the value of recordnumber
var pattern = 'GT-';
var recordnumber = 1; // This value i get dynamically.
var result = pattern + ('00000' + recordnumber).slice(-6);
console.log(result);
The reason you get that result is that you have
var init = 00000;
Note that the zeroes are not in quotes. That is effectively the same as:
var init = 0;
and so when you put it in the string, you get just the one zero.
If you want five zeroes, you need to use a string:
var init = "00000";
If you're trying to zero-pad, in general, this question and its answers that Matt found may be helpful.
But the short version:
var pattern = 'GT-';
var init = "000000"; // Note there are six of these, not five
var recordnumber = 1; // This value i get dynamically.
var result = String(recordnumber);
result = pattern + init.substring(result.length) + result;
Your init is number type, it is already truncated to 0 on assignment.
You need to add leading zeros manually:
function leadzeros(n, size) {
var s = n+"";
while (s.length < size) s = "0" + s;
return s;
}
var pattern = 'GT';
//var init = 00000; // <- here is 'init' is 0 already, so you can drop it
var recordnumber = 1; // This value i get dynamically.
var result = pattern + leadzeros(recodnumber, 5);

How to combine variables of 2 events into one as sum of both. jquery

Basically I'm trying to create simple price calculator. There are 2 functions which calculates price on select event. How I can sum values of these 2 functions into one, and then add it to ".sum" div ?
var xx = j('select[name="miestas"]').change(function(){
var kainos = {"vln":"55", "kns":"150"};
var val = j(this).find(":selected").text();
kaina1 = kainos[val];
return kaina1;
});
var zz = j('select[name="vardas"]').change(function(){
var kainos = {"vln":"35", "kns":"30"};
var val = j(this).find(":selected").text();
kaina2 = kainos[val];
return kaina2;
});
j('select').change(function(){
j('.sum').html(zz + xx); });
Don't return anything from those functions, assign the result to some global variables:
var xx;
var zz;
and inside the handlers:
...
xx = Number(kaina1);
...
zz = Number(kaina2);
Working example:
http://jsfiddle.net/txkmD/1/

How do I combine 2 javascript variables into a string

I would like to join a js variable together with another to create another variable name... so it would be look like;
for (i=1;i<=2;i++){
var marker = new google.maps.Marker({
position:"myLatlng"+i,
map: map,
title:"title"+i,
icon: "image"+i
});
}
and later on I have
myLatlng1=xxxxx;
myLatlng2=xxxxx;
Use the concatenation operator +, and the fact that numeric types will convert automatically into strings:
var a = 1;
var b = "bob";
var c = b + a;
ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:
// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!
warning! this does not work with links.
var variable = 'variable',
another = 'another';
['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');
You can use the JavaScript String concat() Method,
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"
Its syntax is:
string.concat(string1, string2, ..., stringX)
if you want to concatenate the string representation of the values of two variables, use the + sign :
var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1
But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:
function Container(){
this.variables = [];
}
Container.prototype.addVar = function(var){
this.variables.push(var);
}
Container.prototype.toString = function(){
var result = '';
for(var i in this.variables)
result += this.variables[i];
return result;
}
var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1
the advantage is that you can get the string representation of the two variables, bit you can modify them later :
container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3

Categories

Resources