Addition operator isn't working for me in Javascript. If I do 5+5, it gives me 55 instead of 10. How can I fix this?
var numberOne = prompt (Enter first number.);
if (numberOne > 0.00001) {
var numberTwo = prompt(Enter the second number.);
if (numberTwo > 0.00001) {
var alertAnswer = alert (numberOne + numberTwo);
}
}
You're reading in strings, and concatenating them. You need to convert them to integers with parseInt.
IE:
var numberOne = parseInt(prompt("Enter first number."), 10);
There are two main changes that need to take place. First, the prompts must use Strings. Second, you must parse the user's String input to a number.
var numberOne = prompt ("Enter first number.");
if (numberOne > 0.00001) {
var numberTwo = prompt("Enter the second number.");
if (numberTwo > 0.00001) {
var alertAnswer = alert (parseInt(numberOne,10) + parseInt(numberTwo,10));
}
you need to use parseInt
as in
var a = parseInt(prompt("Please enter a number"));
Just for completeness: a potential problem with parseInt() (in some situations) is that it accepts garbage at the end of a numeric string. That is, if I enter "123abc", parseInt() will happily return 123 as the result. Also, of course, it just handles integers — if you need floating-point numbers (numbers with fractional parts), you'll want parseFloat().
An alternative is to apply the unary + operator to a string:
var numeric = + someString;
That will interpret the string as a floating-point number, and it will pay attention to trailing garbage and generate a NaN result if it's there. Another similar approach is to use the bitwise "or" operator | with 0:
var numeric = someString | 0;
That gives you an integer (32 bits). Finally, there's the Number constructor:
var numeric = Number( someString );
Also allows fractions, and dislikes garbage.
Related
I have a problem in JavaScript. Is it possible to check how many numbers are after the decimal point? I tried to do it using a.toString().split(".")[1]), but if there is no decimal point in the number, there is an error. What should I do if I want the system to do nothing if there is no decimal point?
You're on the right track. You can also .includes('.') to test if it contains a decimal along with .length to return the length of the decimal portion.
function decimalCount (number) {
// Convert to String
const numberAsString = number.toString();
// String Contains Decimal
if (numberAsString.includes('.')) {
return numberAsString.split('.')[1].length;
}
// String Does Not Contain Decimal
return 0;
}
console.log(decimalCount(1.123456789)) // 9
console.log(decimalCount(123456789)) // 0
Convert to a string, split on “.”, then when there is no “.” to split on, assume it’s empty string '' (the part you’re missing), then get said string’s length:
function numDigitsAfterDecimal(x) {
var afterDecimalStr = x.toString().split('.')[1] || ''
return afterDecimalStr.length
}
console.log(numDigitsAfterDecimal(1.23456))
console.log(numDigitsAfterDecimal(0))
You could check if no dot is available, then return zero, otherwise return the delta of the lenght and index with an adjustment.
function getDigits(v) {
var s = v.toString(),
i = s.indexOf('.') + 1;
return i && s.length - i;
}
console.log(getDigits(0));
console.log(getDigits(0.002));
console.log(getDigits(7.654321));
console.log(getDigits(1234567890.654321));
The condition you need is:
number.split('.')[1].length
It checks if there are any numbers after the dot which separates the number from its decimal part.
I'm not sure if you are able to use split on numbers though. If not, parse it to a string.
You first need to convert the decimal number to string and then get the count of character after decimal point,
var a = 10.4578;
var str = a.toString();
if(str){
var val = str.split('.');
if(val && val.length == 2){
alert('Length of number after decimal point is ', val[1].length);
} else {
alert('Not a decimal number');
}
}
The output is 4
I am doing an online test and it asks me to write basic javascript code.
It asks me to parse a numberic string and convert it to a number of a different base. It needs me to return -1 if for whatever reason the conversion cannot be done.
I have written this:
function convert(strNumber, radix) {
var result = parseInt(strNumber, radix);
if(isNaN(result))
{return -1;}
return result;
}
Then it runs my code through various tests and all pass. Except one.
Apparently convert("ASD", 15) should be invalid according to the test and it expects it to be -1.
But Javascript happily converts it to number 10
I tried various things such as to add a try{}catch{} block and other things, but javascript never complains about converting "ASD" to base 15.
Is the test wrong, or is parseInt wrong?
By the way strNumber can be any base under 36.
So for instance:
convert("Z", 36) is 35
As I stated in the comment, parseInt will convert up to the point where it fails. So "A" is valid in that radix and "S" is not. So you would need to add a check.
var nums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".substr(0, radix)
var re = new RegExp("^[" + nums + "]+$","i")
if (!re.test(strNumber)) {
return -1
}
parseInt is behaving normally and is converting the letter A into 10 in base 15 (similar to how hex uses A for the number 10). The S and D are discarded, as parseInt accepts this type of malformed input.
From the parseInt documentation:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
As per official documentation the parseInt function behaves as following
For radices above 10, the letters of the alphabet indicate numerals
greater than 9. For example, for hexadecimal numbers (base 16), A
through F are used.
and
If parseInt encounters a character that is not a numeral in the
specified radix, it ignores it and all succeeding characters and
returns the integer value parsed up to that point.
Thus to prevent invalid arguments from being parsed they have to be validated first
function convert(strNumber, radix) {
if (isValidRadix(radix) && isValidInteger(strNumber, radix))
return parseInt(strNumber, radix);
return -1;
}
function isValidInteger(str, radix) {
var letters = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'].slice(0,radix);
str = str.toUpperCase();
for (var i=0; i<str.length; i++) {
var s = str.charAt(i);
if (letters.indexOf(s) == -1) return false;
}
return true;
}
function isValidRadix(radix) {
// 16 up to HEX system
return radix > 0 && radix <= 16;
}
console.log(convert("ASD", 15));
console.log(parseInt("ASD", 15));
console.log(convert("AAA", 15));
1) Why the 155100 is a number here? Just like 255 would be if var s = 155;.
2) Why the 155100 is still a number even if var n = "100"; ?
3) Where and why is var res converted to a number?
What am I missing here?
var s = "155";
var n = 100;
var res = s + n;
document.write(res + "<hr>");
if ( isNaN(res) ) {
document.write("It is not a number");
}
if ( !isNaN(res) ) {
document.write("It is a number");
}
<html>
<head>
<title>stackoverflow.com</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
Thank you so much!
To your questions:
Why the 155100 is a number here? Just like 255 would be if var s = 155;?
It is a string, but when passed to isNaN, that function coerces it to a number and then returns whether that coercion resulted in NaN.
Why the 155100 is still a number even if var n = "100";?
See above. It is not.
Where and why is var res converted to a number?
It is not -- it remains a string.
But as documented on MDN:
When the argument to the isNaN function is not of type Number, the value is first coerced to a Number.
Notes
To check if a variable is of the Number type:
if (typeof res === 'number')
To convert a string to a number, one of these:
i = +res;
i = Number(res);
If you want to only check the start of a string, and not fail if any subsequent characters are not numeric (like 123.45abc), then use:
i = parseFloat(res);
If your interest is only in integers, you can use parseInt, preferably with the second argument to indicate the base. Like with parseFloat, it does not return NaN as soon as the first character passes the test:
i = parseInt(res, 10);
See the MDN link here.
isNaN(res) ---> will be false because 155100 is numeric
typeof res ---> string
Go ahead - try it in your Chrome console right now.
typeof "155100"
isNaN will always return false for a string value regardless of whether or not it can be parsed into a valid number. In order to check if your string is a valid number, you can parse it with parseInt and check if the result is NaN:
var s = "155";
var n = 100;
var res = s + n;
document.write(res + "<hr>");
if ( isNaN(parseInt(res)) ) {
document.write("It is not a number");
} else {
document.write("It is a number");
}
Note: parseInt will only return NaN if the first character cannot be converted to a number. MDN has a "stricter" version here that returns NaN if any part of the string cannot be converted .
JavaScript is a language based upon loose type-interpretation, instead of implicitly requiring type declaration or throwing an error else-wise;
When JavaScript gets a something in quotes, it determines it to be a string; the + operator, with the type now being String, is understood by JavaScript in this context as a string concatenater (concatenation is the combination of two or more things things) and so it happily appends the two together.
Here, you need to do what is known as Type Casting or Type Throwing where you throw(or cast) something into a different type. This is necessary here so that your + operator will behave as you desire
For Example:
var str = "3.14";
var num = new Number(str);
The new keyword is optional, but is recommended for source clarity and readability.
I am making a calculator for fun, but for some reason everything works but the addition.
Instead of adding two numbers, it is writing them both. For example 5 + 7 shows as being 57.
As I said before, -, /, and * are working fine. How should I fix this?
Here is the code:
$('.solve2').click(function(){
var num1 = $('#num').val();
var num2 = $('#number').val();
var ans = num1+num2;
alert(''+ans+'');
});
$('.solve2').click(function(){
var num1 = parseInt($('#num').val());
var num2 = parseInt($('#number').val());
var ans = num1+num2;
alert(''+ans+'');
});
Instead of parseInt, you can use parseFloat as stated in another answer.
EDIT:
As stated in the comments below, it's better to force the string to be interpreted as a decimal number. You can do this by adding the radix parameter.
var radix = 10; //decimal
var num1 = parseInt($('#num').val(), radix);
var num2 = parseInt($('#number').val(), radix);
Use parseFloat, it Parses a string argument and returns a floating point number.
var ans = parseFloat(num1)+parseFloat(num2);
As per your example it was working as cocantenation operator
Convert your values from strings to numbers. The + is both the addition operator and cocantenation operator.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators
Simple, you must cast your string to integer. Use parseInt
var num1 = parseInt($('#num').val());
var num2 = parseInt($('#number').val());
view my sample:
JSFiddle sample
When you get the value of an input element - either via plain JS or using jQuery's .val() - it returns as a string. And when one of the operands of + is a string and the other is a primitive - i.e. a number, string, boolean, undefined or null - then the other one is converted to a string and they are concatenated:
4 + " four" === "4 four"; // true
false + " is now a string" === "false is now a string"; // true
etc.
Therefore, your values returned from .val() are being concatenated, and you need to convert the strings returned from .val() into numbers using parseFloat:
$('.solve2').click(function(){
var num1 = parseFloat($('#num').val()),
num2 = parseFloat($('#number').val()),
ans = num1 + num2;
console.log(ans);
});
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.