I use the following code:
<html>
<head>
<script type="text/javascript">
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( b > c ){alert("The first value more than the second value");}
}
</script>
</head>
<body>
<textarea id="txt"></textarea>
<input type="button" value="Click me" onclick=asd()>
<br>
<textarea id="txt2"></textarea>
</body>
</html>
But the codes work incorrectly.
I am writing the firs textarea, 5.
I'm writng the scnd textarea , 40.
And alarm works. ı dont understand. I searched and find solution.
if( parseInt(b,10)) > (parseInt(c,10)) )
So why has failed the first time?
You're missing quotation marks around the method
<html>
<head>
<script type="text/javascript">
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( b > c ){
alert("The first value more than the second value");
}
}
</script>
</head>
<body>
<textarea id="txt"></textarea>
<input type="button" value="Click me" onclick="asd()">
<br>
<textarea id="txt2"></textarea>
</body>
</html>
It failed the first time because the numbers are parsed as strings.
var b = document.getElementById("txt").value; //b = "5"
var c = document.getElementById("txt2").value; // c = "40"
if( b > c ){ // "5" > "40" is false because the browser will not understand this.
alert("The first value more than the second value");
}
If you use parseInt the strings will be parsed as an integer.
So:
var b = document.getElementById("txt").value; //b = "5"
var d = parseInt(b); // d = 5
The 'is greater/less than' sign will only work with integers ( and floats etc.) but not with strings. That's why the if-statement returned false.
Your code isn't working because you are storing a string. This is why you can't compare them correctly. You need to convert them into integer data types before you can compare them or perform arithmetic operations.
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( parseInt(b) > parseInt(c) ){alert("The first value more than the second value");}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. 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.
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. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
Related
i am kind of new to it all but i have an input field where the user would input a string and i need it to come out split in the right final field depending on numerical and nonnumerical part of the string and no matter what i do it at runtime it only goes through the first IF statement regardless of the length which is my IF statement criteria
<pre>
<p>Click the button to extract characters from the string.</p>
<p id="demo1"></p>
<form>
<input id="userInput"><br>
<label> Non Numeric</label><textarea id="nonNumeric"> </textarea>
<label> Numeric</label><textarea id="numeric"> </textarea> <br>
<label> Numeric Result</label><textarea id="numericResult"> </textarea>
</form>
<button onclick="seventeenDigitChasSearch()">Try it</button>
</pre>
<script>
function seventeenDigitChasSearch() {
var str = document.getElementById("userInput").value ;
var nonNumeric = str.substring(0, 14); //checks between index 0 and 13
var numeric = str.substring(14, 17); ////checks between index 14 and 17
document.getElementById("nonNumeric").innerHTML = nonNumeric;
document.getElementById("numeric").innerHTML = numeric;
//convert the numeric number to an int value before evaluating it
intNumeric =parseInt(numeric) ;
if (intNumeric.toString().length = 17) {
nonNumeric = str.substring(0, 14);
numeric = str.substring(14, 17);
document.getElementById("nonNumeric").innerHTML = nonNumeric;
document.getElementById("numeric").innerHTML = numeric;
document.getElementById("numericResult").innerHTML = "Yaay value is within our of preferred";
}
else if (intNumeric.toString().length = 10) {
numeric = str.substring(0, 10);
document.getElementById("nonNumeric").innerHTML = "none";
document.getElementById("numeric").innerHTML = numeric;
document.getElementById("numericResult").innerHTML = "10 Range";
}
else if (intNumeric == null)
{
document.getElementById("numericResult").innerHTML = "Faulty out of ranged numbers";
}
} ```
The problem is that you are trying to assign 17 to the string length
intNumeric.toString().length = 17
To compare you need to use == or ===
Change the if to if (intNumeric.toString().length == 17) and test again
Here is a reference to the different operators on js. Look at assignation vs comparasion https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
You are making an assignment on if statement. Use = for assignments and == or === for comparisons.
In your case the evaluation of the expression intNumeric.toString().length = 17 return a truthy value.
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context
I try to convert a number with leading zero. JavaScript interpret the number with leading zero as octal number. But I would like to convert the number to string as decimal number and preserve the leading zero. Any idea?
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the formatted number.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var num = 015;
var n = Number(num).toString();
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
try below code
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
document.getElementById("demo").innerHTML = pad(15, 4);
output:
0015
The parseInt() and parseFloat() functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.
+"42"; // 42
+"010"; // 10
+"0x10"; // 16
a = "0042";
alert(typeof +a); // number
alert(+a); // 42
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.
The last days I read how NaN always compares false even with itself and how to compare stuff when NaN may occur, and now I made a JS that compares two NaN true. WTF? Or did I compare 'NaN' strings?
http://www.bksys.at/bernhard/JS-NaN-compare-true.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>radioactivity calculator</title>
</head>
<body>
<form name="form1">
a: <input type="text" name="a"><br>
b: <input type="text" name="b"><br>
x: <input type="text" name="x"><br>
</form>
<script type="text/javascript">
document.form1.a.value=Math.sqrt(-1);
document.form1.b.value=(1/0)/(1/0);
document.form1.x.value=(document.form1.a.value==document.form1.b.value);
</script>
</body>
</html>
You are indeed comparing the string "NaN" against another string "NaN", which equates to true. The value held in text input elements is always pulled as a String type.
A simple way to resolve this is to prefix your values with the Unary Plus (+) operator to convert them to integer values (you can drop those brackets, too):
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
Example
document.form1.a.value = Math.sqrt(-1);
document.form1.b.value = (1/0) / (1/0);
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
<form name="form1">
a: <input type="text" name="a" size="20" value="a"><br>
b: <input type="text" name="b" size="20" value="b"><br>
x: <input type="text" name="x" size="20" value="x"><br>
</form>
Note: As RobG pointed out in his comment below it's important to note here that converting the string value "NaN" to an integer with the Unary Plus operator converts it directly to NaN because the string cannot be replicated as a numeric value. The same would happen if both of your input elements contained the value "Foo" - or even contained two completely different non-numeric string values. Whilst this solution does work, it may yield undesired results if you are to extend this code to handle non-numeric values as well.
This is a JavaScript gotcha ;)
The proper way to compare NaN is to use the isNaN method.
var a = 'a' + 5; //NaN
if (isNaN(a)) {
//do something
}
NaN is a special value in JavaScript. It doesn't even equal itself (also a quick way to test):
var a = parseInt('seven');
if (a == a) {
alert("a == a");
} else {
alert("a != a"); // This will happen
}
if (a == 'NaN') {
// Won't happen
} else {
alert("NaN is not equal to the string 'NaN'"); // Here
}
http://jsfiddle.net/u951v90o/
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.