What is the proper way to add the sum of multiple variables in Javascript?
This is what I'm trying to do. I've tried it with and without the quotes around my variables. I'm not getting a NaN or an Undefined or anything. No output whatsoever.
function setstat(){
document.getElementById('date').value = window.opener.document.getElementById('thisday').value;
document.getElementById('name').value = window.opener.document.getElementById('element_7').value;
document.getElementById('time').value = window.opener.document.getElementById('stwa').value;
inbcalls = window.opener.document.getElementById('element_6').value;
document.getElementById('totinb').value = inbcalls;
inbcallsp = parseInt("inbcalls",10);
asaptotal = window.opener.document.getElementById('asapcalls').value;
document.getElementById('asaptot').value = asaptotal;
asaptotalp = parseInt("asaptotal",10);
faxtotal = window.opener.document.getElementById('faxcalls').value;
document.getElementById('faxtot').value = faxtotal;
faxtotalp = parseInt("faxtotal",10);
obtotal = window.opener.document.getElementById('obcalls').value;
document.getElementById('obtot').value = obtotal;
totalcalls = inboundcallsp + asaptotalp + faxtotalp + obtotalp;
document.getElementById('totsum').value = totalcalls;
}
Why are you quoting the variable names?
inbcallsp = parseInt("inbcalls",10);
should be:
inbcallsp = parseInt(inbcalls, 10);
And the same for the rest of them. You want to parse the value of the variables, not the names of the variables; those will always result in NaN.
asaptotalp = parseInt("asaptotal",10);
"asaptotal" is recognize as the string not the variable
you should not quote it
When using parseInt always specify the radix as 10.
The function singnature: parseInt(string, radix)
The radix is optional but if ommited, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
Example:
parseIn("05") ==== 0 -> true
parseIn("05", 10) ==== 5 -> true
Don't use ParseInt, sometimes it will not return the proper value.
Better use Number, for example:
var i=Number(your value)
Related
I have a simple JS function
let a = 0.33, c=13.89;
var res = calcRound(c*2+calcRound(a*2,1,1),1,1);
console.log(res);
function calcRound(value, figure, padding) {
let val = value;
let result = parseFloat(val);
result = result.toFixed(figure);
return result;
}
It returns a 27.8. But the answer should be 28.5
I have debugged the code. At first, it calculates this and it is correct
calcRound(a*2,1,1) = 0.7
Second time the '+' operator between c*2 and calcRound(a*2,1,1) gets lost.
it becomes like this 27.780.7 which should be like this 27.78+0.7
I know JS first evaluates the expression before sending it as an argument. My question is why the '+' operator is getting omitted?
+ is the concatenator operator in JS, it thinks the result from calcRound() is a string and behaves accordingly.
As mentioned by Andy in the comments, you can see in the
documentation for toFixed()
Return value: A string representing the given number using fixed-point
notation.
Change the return of your function to (to make sure it returns a number):
return Number( result );
let a = 0.33,
c = 13.89;
var res = calcRound(c * 2 + calcRound(a * 2, 1, 1), 1, 1);
console.log(res);
function calcRound(value, figure, padding) {
let val = value;
let result = parseFloat(val);
result = result.toFixed(figure);
return Number(result);
}
It's not getting omitted, JavaScript is treating them like strings and adding 27.78+0.7 as strings, you want to surround them in Number() or parseFloat() statements so that they are treated as numbers.
Like so:
calcRound(parseFloat(c*2) + parseFloat(calcRound(a*2,1,1)),1,1)
i do a simple exercise "Write a JavaScript program to compute the sum of the two given integers. If the two values are same, then returns triple their sum".
InnerHTML is ok but it seems that my variables are string and not numbers (if i use parseFloat however it doesn't work).
Example : p161 = 10; p162 = 5; => ris = 105 and not 15
let p16 = document.getElementById("p16");
document.getElementById("button16").addEventListener("click", es);
function es(){
let p161 = document.getElementById("input161").value;
let p162 = document.getElementById("input162").value;
let ris = 0;
if (p161 == p162){
ris = (p161 + p162)*3;
return p16.innerHTML = ris;
} else {
ris = p161 + p162;
return p16.innerHTML = ris;
}
}
You are concatenating strings so what you see makes sense. Since you are looking for the sum of integers I dont see why you need to parseFloat. If you want numbers you should just do
let p161 = +document.getElementById("input161").value;
let p162 = +document.getElementById("input162").value;
Plus sign in this case is the unary operator that will convert value to Number type according to ECMA spec
I am using the following script. But I am receiving a wrong result for x_b_bbetrag.
When do an calculation exp 100/108 I get 9.92 instead of 92.59.
What am I missing here?
Code below:
var betrag = 100
var kurs = 1
var minkl= 1
var msatz= 0.08
$("#x_b_betrag").change(function() {
var betrag = $("#x_b_betrag").val();
var kurs = $("#x_b_kurs").val();
var minkl =$("input[name='x_b_mwstinkl']:checked").val();
var msatz =$("input[name='x_b_mwst']:checked").val();
if (minkl == "1"){
$("#x_b_rechenbetrag").val((betrag * kurs).toFixed(2));
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + msatz) ).toFixed(2));
}
Use parseFloat
multiplication, division and subtraction automatically parse string to number. for summation you need to parse it.
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + parseFloat(msatz) ) ).toFixed(2));
///1 + "1" = 11 not 2
Parse your inputs into numbers.
For example :
var betrag = parseFloat($("#x_b_betrag").val());
MDN on parseFloat
The value of the msatz variable is not 0.08 but "0.08". It's a string, so when you add one to it, the number will be converted to a string so that they can be concatenated, and the result is "10.08" not 1.08. The string will implicitly be converted to a number when you use it in the division, as it's not possible to divide by a string.
Parse the string into a number:
var msatz = parseFloat($("input[name='x_b_mwst']:checked").val());
A newbie here! Wondering why the following conversion fails!
var num = prompt("Enter num");
alert(num.toString(2));
If num input is 32. I get 32 as num alert message too.
try
(+num).toString(2)
,
Number(num).toString(2)
or
parseInt(num, 10).toString(2)
Any of those should work better for you.
The issue is that the toString method of javascript Number objects overrides the toString method of Object objects to accept an optional radix as an argument to provide the functionality you are looking for. The String object does not override Object's toString method, so any arguments passed in are ignored.
For more detailed information about these objects, see the docs at Mozilla:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Methods
or W3 schools:
http://www.w3schools.com/jsref/jsref_tostring_number.asp
http://www.w3schools.com/jsref/jsref_obj_string.asp
With this function you can specify length of the output.
For example decbin(7,4) produces 0111.
function decbin(dec,length){
var out = "";
while(length--)
out += (dec >> length ) & 1;
return out;
}
demo
Here is my solution that does not use parseInt, but rather a method that shows the logic behind the conversion of decimal to binary.
This method prints the bits to the array which you may later print out if you wish:
var number = 156;
var converted = [];
while(number>=1) {
converted.unshift(number%2);
number = Math.floor(number/2);
}
The converted array will now appear like so:
[1,0,0,1,1,1,0,0]
which of course converts back to 156.
/**
Convert a decimal number to binary
**/
var toBinary = function(decNum){
return parseInt(decNum,10).toString(2);
}
/**
Convert a binary number to decimal
**/
var toDecimal = function(binary) {
return parseInt(binary,2).toString(10);
}
Finally use it
var num= prompt("Enter num");
alert(toBinary(num));
Cast it to an integer first. At the moment you're converting a string to it's binary representation.
num = +num;
I know that 0x is a prefix for hexadecimal numbers in Javascript. For example, 0xFF stands for the number 255.
Is there something similar for binary numbers ? I would expect 0b1111 to represent the number 15, but this doesn't work for me.
Update:
Newer versions of JavaScript -- specifically ECMAScript 6 -- have added support for binary (prefix 0b), octal (prefix 0o) and hexadecimal (prefix: 0x) numeric literals:
var bin = 0b1111; // bin will be set to 15
var oct = 0o17; // oct will be set to 15
var oxx = 017; // oxx will be set to 15
var hex = 0xF; // hex will be set to 15
// note: bB oO xX are all valid
This feature is already available in Firefox and Chrome. It's not currently supported in IE, but apparently will be when Spartan arrives.
(Thanks to Semicolon's comment and urish's answer for pointing this out.)
Original Answer:
No, there isn't an equivalent for binary numbers. JavaScript only supports numeric literals in decimal (no prefix), hexadecimal (prefix 0x) and octal (prefix 0) formats.
One possible alternative is to pass a binary string to the parseInt method along with the radix:
var foo = parseInt('1111', 2); // foo will be set to 15
In ECMASCript 6 this will be supported as a part of the language, i.e. 0b1111 === 15 is true. You can also use an uppercase B (e.g. 0B1111).
Look for NumericLiterals in the ES6 Spec.
I know that people says that extending the prototypes is not a good idea, but been your script...
I do it this way:
Object.defineProperty(
Number.prototype, 'b', {
set:function(){
return false;
},
get:function(){
return parseInt(this, 2);
}
}
);
100..b // returns 4
11111111..b // returns 511
10..b+1 // returns 3
// and so on
If your primary concern is display rather than coding, there's a built-in conversion system you can use:
var num = 255;
document.writeln(num.toString(16)); // Outputs: "ff"
document.writeln(num.toString(8)); // Outputs: "377"
document.writeln(num.toString(2)); // Outputs: "11111111"
Ref: MDN on Number.prototype.toString
As far as I know it is not possible to use a binary denoter in Javascript. I have three solutions for you, all of which have their issues. I think alternative 3 is the most "good looking" for readability, and it is possibly much faster than the rest - except for it's initial run time cost. The problem is it only supports values up to 255.
Alternative 1: "00001111".b()
String.prototype.b = function() { return parseInt(this,2); }
Alternative 2: b("00001111")
function b(i) { if(typeof i=='string') return parseInt(i,2); throw "Expects string"; }
Alternative 3: b00001111
This version allows you to type either 8 digit binary b00000000, 4 digit b0000 and variable digits b0. That is b01 is illegal, you have to use b0001 or b1.
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
for(var i = 0; i < 256; i++)
window['b' + i.toString(2)] = window['b' + i.toString(2).lpad('0', 8)] = window['b' + i.toString(2).lpad('0', 4)] = i;
May be this will usefull:
var bin = 1111;
var dec = parseInt(bin, 2);
// 15
No, but you can use parseInt and optionally omit the quotes.
parseInt(110, 2); // this is 6
parseInt("110", 2); // this is also 6
The only disadvantage of omitting the quotes is that, for very large numbers, you will overflow faster:
parseInt(10000000000000000000000, 2); // this gives 1
parseInt("10000000000000000000000", 2); // this gives 4194304
I know this does not actually answer the asked Q (which was already answered several times) as is, however I suggest that you (or others interested in this subject) consider the fact that the most readable & backwards/future/cross browser-compatible way would be to just use the hex representation.
From the phrasing of the Q it would seem that you are only talking about using binary literals in your code and not processing of binary representations of numeric values (for which parstInt is the way to go).
I doubt that there are many programmers that need to handle binary numbers that are not familiar with the mapping of 0-F to 0000-1111.
so basically make groups of four and use hex notation.
so instead of writing 101000000010 you would use 0xA02 which has exactly the same meaning and is far more readable and less less likely to have errors.
Just consider readability, Try comparing which of those is bigger:
10001000000010010 or 1001000000010010
and what if I write them like this:
0x11012 or 0x9012
Convert binary strings to numbers and visa-versa.
var b = function(n) {
if(typeof n === 'string')
return parseInt(n, 2);
else if (typeof n === 'number')
return n.toString(2);
throw "unknown input";
};
Using Number() function works...
// using Number()
var bin = Number('0b1111'); // bin will be set to 15
var oct = Number('0o17'); // oct will be set to 15
var oxx = Number('0xF'); // hex will be set to 15
// making function convTo
const convTo = (prefix,n) => {
return Number(`${prefix}${n}`) //Here put prefix 0b, 0x and num
}
console.log(bin)
console.log(oct)
console.log(oxx)
// Using convTo function
console.log(convTo('0b',1111))