I am writing a function that needs to be able to tell the difference between the numbers 01 and 1. I am doing a cubical search within a company directory and on the same floor there are cubicles numbered 01 and 1. When the cubical search returns 01 it automatically assumes the value is a 1 and not '01'.
Is there a method or something I could use to differentiate between '01' and '1'.
Thanks.
There is no difference between the numbers 01 and 1. They are absolutely identical.
console.log(01 === 1);
There is a difference between the strings "01" and "1". If you need to distinguish between the values, then use strings, not numbers.
console.log("01" === "1");
Is there a method or something I could use to differentiate between '01' and '1'.
Yes, string comparison.
When you treat these two values as strings then these two values will be different
var isEqual = '1' === '01'; // false
Only by converting them to numbers will they evaluate the same and be indistinguishable.
These aren't really NUMBERS, they are CHARACTER STRINGS, whose characters all happen to be digits.
I presume that you are doing a "cubicle search" - a search for a cubicle (those little pens that companies keep people in), rather than some sort of mathematical search that involve cubes
You will treat both inout as strings. Consider this:
var x = "01";
var y = "1";
var z;
if (x === y) {
return true;
} else {
return false;
}
Note there is a difference between == (value only) and === (value and type)
Related
This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 5 years ago.
var check = true;
var number = Math.floor(Math.random() * 20);
while (check === true){
var guess = prompt("I picked a number 0 to 20, try to guess it!");
if (number === guess) {
print("You guessed correctly! Good job!");
check = false;
}
else if (number < guess) {
print("\n\You guessed too high!");
}
else if (number > guess) {
print("\n\You guessed too low!");
}
else {
print("\n\Error. You did not type a valid number");
exit();
}
print("\n\Guess: " + guess + ".");
}
When I try running this program, I get all the way up to the correct answer, but it doesn't work! Even if the randomly generated number is 13, and I guessed 13, it would go through and it would say it is invalid.
Your guess is a string. It is the text entered by the user you need to convert it into a number in order to be able compare it with your guess so replace
var guess = prompt("I picked a number 0 to 20, try to guess it!");
with
var guess = Number(prompt("I picked a number 0 to 20, try to guess it!");
This will turn your guess from your user into a number or a special value NaN if it isn't formatted correctly.
You could also use the == operator which will automatically convert between types. I would recommend against using the operator if you are new to javascript as it can have some confusing and unexpected behaviors.
You are comparing the return value of prompt (a string) with the return value of Math.floor (a number).
Since you are using === and they are different data types, you'll never get a match.
Use == or explicitly cast the number to a string or vice versa.
number === +guess
=== is strictly typed so it will not compare the int to a string.
Convert guess to an integer. You should first validate it though in case the user inputs something other than an int.
var guessInt = +guess; // the plus converts to an integer
if(isNaN(guessInt))
continue;
if (number === guessInt) {
print("You guessed correctly! Good job!");
check = false;
}
You are using the triple = operator which checks for type equalness too. when you compare the prompt value (your guess variable) to your number variable. you are comparing a String and a Number. To make this work you could use
number == guess
or
Number(guess)
You’re using strict equality comparison, which also compares types.
prompt returns string values. Use parseInt to cast to a number.
var guess = prompt("I picked a number 0 to 20, try to guess it!");
guess = parseInt(guess, 10);
The second parameter tells the number base (10 is for decimal, 16 for hexadecimal, etc.). In non strict mode (aka sloppy mode) you may experience accidental conversion to octal (base 8) when parsing strings with a leading zero. Always specify the base to avoid this.
You might want to learn more about JavaScript strict mode.
var num = Number(prompt("Pick a number", "0"));
if (num < 10)
alert("Small");
else if (num < 100)
alert("Medium");
else
alert("Large");
I'm just confused about what the Number is doing in this code.
What will happen if I make it like this:
var num = prompt("Pick a number", "0");
Number converts the passed value to a number value. Examples:
> Number(10)
10
> Number("10")
10
> Number(true)
1
> Number("0x11")
17
> Number("foo")
NaN
It performs explicit type conversion to a number.
There is also String and Boolean which do basically the same, but convert to a string and boolean instead.
What will happen if I make it like this ...
prompt will always return a string value. However, in your specific example, it wouldn't actually make a difference because the relational comparison operator (<) will perform the same type conversion implicitly. I.e.
a < 10
// is the same as
Number(a) < 10
Still, I'd say it's good practice to perform explicit type conversion, since it makes it clearer in the rest of the code what type you expect.
Note: It is also possible to call Number with new, i.e. new Number(...), however, that will return a number object instead of primitive number value. This is rarely used.
There is two value 'a' and 'b'. i need to check a is greater than 'b'
if it is a big value its check the greater values. but here difference only in point values. it ignore point values
var a='20.796';
var b='20.190';
if (parseInt(a) > parseInt(b))
{
alert("function can work");
return false;
}
You parse your numbers as integers. You want rational/real numbers instead. Use parseFloat:
var a = '20.796';
var b = '20.190';
console.log(parseInt(a,10),parseInt(b,10));
console.log(parseFloat(a),parseFloat(b));
Result:
20 20
20.769 20.190
Also, please always use the radix argument if you use parseInt(string [, radix]).
Furthermore - if a and b are numbers, don't save their values in a string. It's much easier to save their values instead:
var a = 20.796;
var b = 20.190;
It's ignoring point values because you are parsing them as integers in the if statement conditional. You have a couple options.
Define the variables as floats instead of strings; remove the parseInt function calls.
Exchange the parseInt for parseFloat calls.
Here, your solution is to parse the strings as floating points rather than integers. For example:
var a = '20.796',
b = '20.190';
if (parseFloat(a) > parseFloat(b)) {
// TODO: .. code ..
}
Your code right now is parsing the strings as integers. Integers are whole number values and CANNOT contain a decimal value, meanwhile floats or floating point numbers CAN contain a decimal value. When you call 'parseInt()' on the floating point, it truncates (or removes) the decimal value and just keeps the whole value. Which is obviously not what you're looking for.
PS: I'm guessing you're new to JavaScript, and so I just want to wish you good luck with learning it. Personnaly, I find JavaScript to be a very beautiful language if you learn it well.
Define your numbers as numbers, and remove the call to parseInt or use parseFloat.
var a=20.796;
var b=20.190;
if (a > b)
{
alert("function can work");
return false;
}
or
if (parseFloat(a) > parseFloat(b))
{
alert("function can work");
return false;
}
I am trying to sort date-time strings using Regex in my javascript code but am running into a problem. If the HH portion of the string "MM/DD/YYYY HH:MM:SS" is one digit, my program sorts that with a missing digit and is therefor a way smaller number and does not sort properly.
My regex is this (the part in question is in bold):
/^(\d{ 1,2 })[/- ](\d{ 1,2 })[/- ](\d{ 4 })[\s](\d{ 1, 2})[\:](\d{ 2 })[\:](\d{ 2 })[\s]([ AP]M)?/g
Is there a way to add a zero to the front of the HH if the number is one digit? And without using any .replace() methods, because that wont work in the section of my sort function.
Thanks in advance!
You can't modify the string without using replace. You can "normalize" a date that matches your regex:
var out = old
.replace(/^(\d\d?)[\/ -](\d\d?)[\/ -](\d{4})\s(\d\d?):(\d\d):(\d\d)(?:\s([AP]M))?/g
,function(x,m,d,y,h,i,s,a) {
if( m.length == 1) m = "0"+m;
if( d.length == 1) d = "0"+d;
if( a == "PM") h = ""+((h%12)+12);
if( a == "AM" && h == 12) h = "0";
if( h.length == 1) h = "0"+h;
return y+m+d+h+i+s;
});
For today's date, this would return:
20121130141320
The date components are sorted from biggest to smallest, which means a simple .sort() call would arrange the dates in the right order with no fuss.
NOTE: I edited your regex a little, but it still matches the same stuff. The only difference is that now if there is no AM or PM, the space at the end is no longer required.
Can you call a custom sort function that converts the strings into Date objects to compare them?
Similar to: Sort Javascript Object Array By Date
I'm kind of late on the subject, but personnally, I don't feel like using regex on this. I do prefer keep things simplier when I can, hence the use of ternary operators :
// now (I'm posting at 03/05, so let's take this value)
var datev = new Date();
/*
* here we will simply concatenate the value with a prefix "0" if the number
* is lower than 10. If not, concatenate the original value.
*/
var string_date = (datev.getMonth()+1 < 10 ? "0"+datev.getMonth()+1 : datev.getMonth()+1) + "/" + (datev.getDate() < 10 ? "0"+datev.getDate() : datev.getDate());
// display 03/05 instead of 3/5
console.log(string_date);
Wanted to add this method to bring some variety on the topic.
Note : The getMonth() return a value between 0 and 11 so you have to add 1 to it in order to get the correct value.
I understand that using the "===" compares type, so running the following code results in "not equal" because it's comparing a number type to a string type.
var a = 20;
var b = "20";
if (a === b) {
alert("They are equal");
} else {
alert("They are not equal");
}
But I dont understand how using the "==" to compare only the value results in the "They are equal" message.
var a = 20;
var b = "20";
if (a == b) {
alert("They are equal");
} else {
alert("They are not equal");
}
How are the values equal? Isn't the string "20" stored as the ASCII characters 50 and 48 (0110010 and 0110000 in binary) and 20 stored as the actual binary number 0010100?
EDIT: Thanks everyone! I think all the responses are great and have helped me understand this much better.
The == operator compares only the values of the variables. If the types are different, a conversion is operated. So the number 20 is converted to the string "20" and the result is compared.
The === operator compares not only the values, but also the types, so no cast is operated. In this case "20" !== 20
The JavaScript engine sees the a as a number and casts the b to number before the valuation.
When type conversion is needed, JavaScript converts String, Number, Boolean, or Object operands as follows.
When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.
The problem with the == comparison is that JavaScript version 1.2 doesn't perform type conversion, whereas versions 1.1 and 1.3 onwards do.
The === comparison has been available since version 1.3, and is the best way to check of two variables match.
If you need your code to be compatible with version 1.1, 1.2 and 1.3 versions of JavaScript code, you should ensure that the variables all match as if it was an === comparison that was being performed.
Part of the definition of "==" is that the values will be converted to the same types before comparison, when possible. This is true of many loosely typed languages.
Javascript is designed such that a string containing numbers is considered "equal" to that number. The reason for that is simplicity of use for the case of users entering a number into an input field and the site validates it in JS -- you don't have to cast the entered string to a number before comparing.
It simplifies a common use case, and the === operator still allows you to compare with the type considered as well.
As far as I know JavaScript does automatic data type conversion on the fly - so maybe the variables are casted to equivalent types automatically.