Matching float and string value in javascript not matched - javascript

I am using this code
if(total == balance)
{
alert("test ok");
}
else
{
alert("test failed");
}
here total=10; and balance=10.00; but the result is "test failed".

Hmm... I may not be exactly correct, but I think total is taken as an integer and balance is taken as a decimal. Try the === function instead of the == function.
The === function converts the values and then checks them.
So checking if a value is true or false depending on whether it is 0 or 1 requires the === operator to convert both into the same type of values.
And the == function just checks whether two values are equal, just by looking at the present value of it. No conversion. So if I want to check the values of two int values, I will use ==.
There are two ways to solve this problem.
One is by changing either the total into a decimal, by giving it a value of 10.00 with a decimal or changing the balance into an int by giving it a value of 10, without the decimal places.
The other is the better one, and you just have to replace your == with a ===. So your code would look like this:
if (total === balance) {
window.alert("test ok");
} else {
window.alert("test failed");
}

Related

How do I check if a variable is null, so that I can change it later on?

A group of me and two other people are working to make a Jeopardy game (themed around United States History questions) all in JavaScript. For our final Jeopardy screen, the two teams will each bet a certain amount of money. To prevent a team from typing in random letters for a bet (i.e typing in "hasdfhgasf" instead of an actual amount), we're trying to write an 'onEvent' command that checks to see if a bet is null. If that bet is null, then the code should come up with a message on the screen that tells them to check their bets again.
We tried using statements like, if "null" or if " " but neither of these statements works. We've worked with using getNumber and getText commands, along with just regular variable comparisons with or booleans. So far, we haven't had any luck with these methods.
Here's the group of code we're having issues with:
onEvent("finalJeopardyBetSubmit", "click", function() {
team1Bet = getNumber("team1BetInput");
team2Bet = getNumber("team2BetInput");
console.log(team1Bet);
console.log(team2Bet);
if (getText("team1BetInput") == "" || getText("team2BetInput") == "") {
console.log("Check bet!");
finalJeopardyError();
} else if ((getText("team1BetInput") != 0 || getText("team2BetInput") != 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") < 0 || getNumber("team2BetInput") < 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") > team1Money || getNumber("team2BetInput") > team2Money)) {
console.log("Check bet!");
finalJeopardyError();
} else {
console.log("Done");
}
});
You can also check out the whole program on Code.org if you'd like to get a better look.
We expect that with the console.log commands, it should say "check bet" if the bets return as null. Instead, the code has ended up fine, and not displaying our error message, even if we type in nothing or just random letters.
a null variable will evaluate to false. Try:
if(variable){
// variable not null
}else{
// variable null
}
Convert the value to a Number first using Number(value) and then check for falsy values using the logical not ! operator. If they enter alphabetic characters, then calling Number('abc') results in NaN.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null; NaN; 0; empty string ("" or '' or ``); undefined.
The ! will change any of the falsy values above to true, so you can check for all of them with just the first if statement below.
onEvent("finalJeopardyBetSubmit", "click", function() {
// Convert these values to numbers first
var team1Bet = Number(getNumber("team1BetInput"));
var team2Bet = Number(getNumber("team2BetInput"));
if (!team1Bet || !team2Bet) {
// Handle invalid number error
}
else if (team1Bet < 0 || team2Bet < 0) {
// Handle invalid range error
}
else if (team1Bet > team1Money || team2Bet > team2Money) {
// Handle insufficient funds error
}
else {
// Finish game
}
})
You can read more about the logical operators here.

How do I modify a function to return true if the given decimal is even when it is rounded to an integer and false otherwise?

I'm working on a Javascript exercise. I am trying to modify a function to return true when the given decimal is rounded to an even number and false when it is not.
So far I have
function isRoundedNumberEven(decimal){
}
console.log(isRoundedNumberEven(2.2), '<-- should be true');
console.log(isRoundedNumberEven(2.8), '<-- should be false');
You have described two steps.
Round the number. This is easily achieved with Math.round()
Determine if it's even or odd. The easiest way to determine this is to divide by 2 and check the remainder. If the remainder is zero, then the number is even. Otherwise, it is odd.
The way you do this is using the modulo operator % - in this case, roundedNumber % 2 would give you the remainder when dividing by 2.
You just need to check if this remainder is 0 or 1, and since you want to "return true if the number is even," then the easy way is return roundedNumber % 2 === 0;
I've provided the tools. Over to you now to assemble them in the right way.
There are two key functions you need here: Math.round(decimal) and the modulo function: "%".
The first will round a decimal value. So, Math.round(2.2) == 2, and Math.round(2.8) == 3.
The second will find the remainder after whole-number division of a number. So, 2%2 == 0, and 3%2 == 1.
Hence, the contents of your function should be:
return Math.round(decimal) % 2 === 0;
function isRoundedNumberEven(decimal){
if((Math.round(decimal)%2) == 0) {
return true;
}
return false;
}

How do you get a if statement between an Element and Infinity?

I want to be able to have an if statment saying that if an element is equal to Infinity, it gives out a different phrase than "Infinity"(my element is an input box) here is my if statement:
if (document.getElementById("box").value === Infinity) {
document.getElementById("box").value = "STOP PRESSING BUTTONS"
}
I'm still very new to javascript/html so I might've gotten some of the terms wrong.
Try this...
if (result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY)
{
// ANY LOGIC
}
You could possibly use the isFinite function instead, depending on how you want to treat NaN isFinite returns false if your number is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN.
if (isFinite(result))
{
// ANY LOGIC
}

Checking only the integer values through Regex

My Code:
I tried the following code
<SCRIPT type="text/javascript">
var num = "10";
var expRegex = /^\d+$/;
if(expRegex.test(num))
{
alert('Integer');
}
else
{
alert('Not an Integer');
}
</SCRIPT>
I am getting the result as Integer. Actually I declared the num varibale with double quotes. Obviously it is considered as a string. Actually I need to get the result as Not an Integer. How to change the RegEx so that I can get the expected result.
In this case, it should give the result as Not an Integer. But I am getting as Integer.
if(typeof num === "number" &&
Math.floor(num) === num)
alert('Integer');
else
alert('Not an Integer');
Regular expressions are there to work on strings. So if you tried it with something else than a string the string would either be converted or you would get an error. And yours returns true, because obviously the string only contains digit characters (and that is what you are checking for).
Use the typeof operator instead. But JavaScript doesn't have dedicated types for int and float. So you have to do the integer check yourself. If floor doesn't change the value, then you have an integer.
There is one more caveat. Infinity is a number and calling Math.floor() on it will result in Infinity again, so you get a false positive there. You can change that like this:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num)
...
Seeing your regex you might want to accept only positive integers:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(Math.abs(num)) === num)
...
RegExp is for strings. You can check for typeof num == 'number' but you will need to perform multiple checks for floats etc. You can also use a small bitwise operator to check for integers:
function isInt(num) {
num = Math.abs(num); // if you want to allow negative (thx buettner)
return num >>> 0 == num;
}
isInt(10.1) // false
isInt("10") // false
isInt(10) // true
I think it's easier to use isNaN().
if(!isNaN(num))
{
alert('Integer !');
}
else
{
alert('Not an Integer !');
}
Léon

How to store more than 10 digit number in javascript using the var?

First of all,
What am i doing ?
I have to set the limit of emails in our product in webpage.It's handled with the javascript for validation.It handles upto 8 digit numbers fine. But in our QA team enters the more than 17 digit number in the text box of other email field.It throw the negative message.What can i do ???
My sample code is:
if(form.otherEmails) {
if(validEmailArray.endsWith(',')){
var otherEmailLength = validEmailArray.substring(0,validEmailArray.length-1).split(",");
var setLimitOtherEmail = window.parent.document.getElementById('setLimitOtherEmail').value;
if(setLimitOtherEmail == '-1'){
form.otherEmails.value = otherEmailLength;
}
else if(otherEmailLength.length <= setLimitOtherEmail){
form.otherEmails.value = otherEmailLength;
}
else{
alert("More than "+setLimitOtherEmail+ " " +"Recipient emailIds not allowed in this section.\nIf you want to send it to more recipients, Please create a Bulk Contact Group.");
form.otherEmails.focus();
return false;
}
}
else
form.otherEmails.value = validEmailArray;
}
This is due to the limit being a string, and when a string is being compared to a number (length) the number is coerced into a string, not the other way around.
These are then compared lexicographically - and lexicographically "9" is more (>) than "19".
You need to use parseInt(setLimitOtherEmail, 10) to get the value as a number before comparing them.
Try parsing each of the numbers into Integers before performing any comparison operations on them.
var setLimitOtherEmail = parseInt(window.parent.document.getElementById('setLimitOtherEmail').value);
Other than that are you certain otherEmailLength is actually the number that you want? From the looks of it you are taking the substring of validEmail array and splitting it on "," but it doesn't look like you actually get the length of the array. Try adding .length to the end of the value of otherEmailLength.
var otherEmailLength = validEmailArray.substring(0,validEmailArray.length-1).split(",").length;

Categories