Javascript templete literals not working with random number generator - javascript

I'm trying to generate a random number and then if the user enters the same num he can move forward otherwise it will generate another random number. But the template literal to generate random num (a) is not working.
var a = Math.floor(Math.random()*10); // Random num generator
var userInput = alert('Enter the numbers: ${a}'); // User input
while ( userInput !== a){ // Loop
alert("Try Again!");
userInput = alert('Enter the numbers: ${a}');
};

There are a few things that can be improved in your code.
Naming your number variable a instead of n is confusing.
Math.floor can be shorted to ~~ in your case (not every case).
You get user input from prompt, not alert, which merely shows a message.
You're using the strict equality !== operator to compare your random number with the user's input, which will always be a number in String form. So even if they enter the correct number, it will be interpreted as incorrect, since '3' is not strictly equal to 3. You have to use != instead.
There's no need for a userInput variable since you're only doing one thing with it. Just inline the prompt inside the condition of the while loop.
Since n never changes, declare it with const so that if you accidentally try to change it later, you will get an error to bring this to your attention.
As someone noted in the comments, string literals use `, not '.
const n = ~~(Math.random() * 10);
while (prompt(`Enter the number: ${n}`) != n) {
alert('Try again!');
};

Related

Javascript: Why won't my values equal up? [duplicate]

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.

+prompt vs prompt in JavaScript

Is it good to use +prompt instead of just regular prompt in JavaScript if I want only integer numbers to be typed in my prompt window? Does it say something like that about +prompt in the JavaScript standard/rules ?
Well this is what happen's when you add plus before prompt, i.e. as below,
Eg :- 1
var a = prompt("Please enter a number");
console.log(a);
typeof(a);
Now in eg (1) when you enter a number and if you check that in console, it show a number but as that number is in-between double-quote, so in JavaScript it's a string, that's what it will show in typeof too when you console that.
Eg :- 2
var a = +prompt("Please enter a number");
console.log(a);
typeof(a);
Now when you console the var a and typeof a of eg(2) the result differs as we have added + before prompt. So this time we get our prompt input value as number and not string. Try you will understand what I'm saying.
No.
The unary plus operator will convert the response in to a Number, not an integer.
It could give you a floating point value, it could give you NaN.
If you want an integer then you need to check the response and then put in some error recovery for cases where the response is not what you want.
For example: If it is a floating point value, then you might want to just use Math.floor to convert it. If it is NaN then you might want to prompt the user again.
The effect of +promt("...") is that the result of the promt command will be cast to a number.
This is a nice hack, but not a clean solution.
I would recommend to assign the user input to a variable, then check it and in case it doesn't match the requirements, throw an exception or error message.
var
input = prompt("Please enter a positive number"),
inputNum = parseInt(input, 10);
if (isNaN(inputNum) || inputNum < 1)
alert("You did not enter a positive number.");
So putting a + before any data type converts it into a number.
I tried this:
typeof(+"100") ==> number
typeof(+"12.34") ==> number
typeof(+true) ==> number
typeof(+false) ==> number
Things got really weird when I experimented with the undefined data type. e.g.:
x = +undefined
typeof(x) ==> Number whilst value of variable x is NaN
+prompt() is just a + before a prompt(), it's like writing +"3" or +"10". It just tries to cast the outcome to a number.

Input box with accounting.js formatting not letting me input decimal numbers

On my website satoshindex.com when I try and type a number with a decimal point into the top input box, it automatically deletes the decimal point. It also doesn't let me highlight the input with Ctrl-A or use the arrow keys to move to a different digit in the number.
I think it has something to do with accounting.js.
Here is the relevant code from my website:
var SAT = 0.00000001;
var BIT = 0.000001;
var MBIT = 0.001;
var BTC = 1;
var currentUnit = BTC;
I know it has something to do with these lines in the btcConvert and usdConvert functions because when I delete them the issue goes away but no commas are used to separate the numbers.
var decimals = decimalPlaces(input.value);
input.value = accounting.formatNumber(input.value, decimals)
I think the issue is that btcConvert is called every time you type in the input box and formatNumber is deleting the decimal place, but without formatNumber in btcConvert I can't get it to add commas to the number when it is above 999, same in USD convert.
You can actually enter a decimal number like 1234.5 if you type the .5 really fast or if you copy-paste it into the input field. With normal typing speed, 1234. always turns into 1234 before you can add the 5. As you suspect, accounting.js is simplifying the 1234. to 1234 because that is what it considers to be the canonical format.
So you want to make it possible for the user to type 1234.0 and have it automatically formatted to 1,234.0 in the input field. I see three possible approaches:
Modify the accounting.js code. Edit accounting.formatNumber so that it doesn't discard the decimal point when it's the final character of input.value.
Don't use accounting.js to format the input field. Replace the call to accounting.formatNumber with a call to a formatting function that you write yourself.
A quick and dirty solution: Don't modify accounting.js and keep the call to accounting.formatNumber, but if input.value had a decimal point at the end and you get back a string without the decimal point, stick it back on.
One way to apply the quick and dirty approach to btcConvert is to replace this line:
input.value = accounting.formatNumber(input.value, decimals)
With this:
var formatted = accounting.formatNumber(input.value, decimals);
if (input.value.indexOf('.') == input.value.length - 1 &&
input.value.length != 0 &&
formatted.charAt(formatted.length - 1) != '.') {
formatted += '.';
}
input.value = formatted;
The check for input.value.length != 0 is necessary because if input.value is the empty string, indexOf will always return -1, which is equal to input.value.length - 1 for empty input.value.

how to convert string into integer in uiautomation?

I am extracting a value from a text field (using .value()) and then I want to add a number to it so that I can check another value with result of above combination. At present, when I am adding number to it, so its getting appended to it. For eg, if value is 55 and I am adding number 1 to it, so result is 551 instead of 56. This is because its taking is as string and then appending it, so does anybody know a method to convert string to integer in javascript for UIAutomation?
Javascript provides the parseInt() function for converting Strings to Integers.
var strNum = "3";
var num = parseInt(strNum,10);
(typeof num == "number") ? alert("Is a number"):alert("Not a Number");

Why do strings sometimes get changed to numbers in javascript?

I have this code:
function getSessionGUID() {
return (S4()+S4());
}
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
It clearly returns a string, but if you run it a bunch of times, you can notice that it sometimes returns infinity.
for (var i = 0; i < 100000; i++){ if(getSessionGUID() == Infinity) console.log("INFINITY"); }
871 x INFINITY
I then noticed that if you remove the |0, it solves the problem:
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
Results:
for (var i = 0; i < 100000; i++){ if(getSessionGUID() == Infinity) console.log("INFINITY"); }
undefined
Why does this happen? In both cases the value is changed into a string.
You are generating hexidecimal strings.
When you use the == operator, the interpreter tries to coerce the two values to the same data type. When comparing strings to Infinity, that intermediate data type is Number. When those strings contain the letter "e" (a valid hexidecimal digit) and they're coerced to a Number, javascript interprets this as 10^x which ends up as some huge number.
Numbers in javascript are 8 bytes, so anything larger than 1.7976931348623157e308 is considered equal to Infinity.
The easiest way to fix this is to change your == to === so the string doesn't get coerced to a number.
if(getSessionGUID() === Infinity)
http://jsfiddle.net/Uhkxm/
This test reveals the answer:
for (var i = 0; i < 100000; i++){
var x=getSessionGUID();
if(x == Infinity) console.log(x); }
}
It logs values like 61e93284 or 1413e390
These values are valid numbers and they are way too big for the Number type, so they get cast as Infinity when interpreted as a number.
If you replace == with === in the test, no conversion occurs and nothing is logged. The conversion is caused by the == operator.
I think I figured it out. There's actually nothing wrong in all of this, except on my test code.
If you take this string "11e51354", you can get it to assert to true since Javascript checks for all the types that could make it equal to true.
"11e51354" == Infinity # True
The right test would be:
"11e51354" === Infinity # False
It's still a string, but somehow while I was sending it through a GET request, it was being transformed into a number type which gave Infinity.
JavaScript is dynamically typed. There isn't an integer, floating point. String data type. All of that conversions is done internally depending on the context.
The + could be string concatenation or addition depending on context.
Edit: Apologies. Too late. But it was the == performing the conversion to number when comparing against infinity. In some cases, you generated valid numbers.
If you really need a number type, you always could use following.
console.log(Number("1"));

Categories