I made a simple number guessing game in javascript which goes from 1 to 100.
My problem is that everything works, except when I type a decimal number from 100 to 101. I want my code to give me the "Please enter a number from 1 to 100" message then, but it doesn't.
How do I get Javascript to round this properly?
let randomNumber = Math.floor(Math.random() * 100); // Random number
function guess() {
let inp = document.getElementById("number").value; // Reading input
let inpRounded = Math.floor(inp);
// Random number is higher
if (inpRounded < randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "Higher";
}
// Random number is lower
else if (inpRounded > randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "Lower";
// Input matches random number
} else if (inpRounded == randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "You won!";
}
// Input is weird
else if (inpRounded == null) {
document.getElementById("result").innerHTML = "Please enter a valid number";
}
// Input is lower than 1 or higher than 100
else if (inpRounded < 1 || inpRounded > 100) {
document.getElementById("result").innerHTML = "Please enter a number from 1 to 100";
}
// Other issue
else {
document.getElementById("result").innerHTML = "Error"
}
}
<h2>Enter a number from 1 to 100</h2>
<input type="number" placeholder="Type your guess here" id="number">
<input type="button" value="Go!" onclick="guess()">
<p id="result"></p>
Don't round the number initially, otherwise you'll lose the decimal information you need when you want to reject values between 100 and 101.
function guess() {
const value = document.getElementById("number").value; // Reading input
const numValue = Number(value);
if (numValue < 1 || numValue > 100) {
document.getElementById("result").textContent = "Please enter a number from 1 to 100";
return;
}
const inpRounded = Math.floor(numValue);
// etc
Just put this code first before you check other things.
if (inpRounded == null) {
document.getElementById("result").innerHTML = "Please enter a valid number";
return;
}
if (inpRounded < 1 || inpRounded > 100) {
document.getElementById("result").innerHTML = "Please enter a number from 1 to 100";
return;
}
In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();
I am having some troubles with js code. I need to prompt the user to enter a valid number (between 0 and 120). If the entry is invalid, it should just display the starting prompt. However, if the user enters "-1", it should terminate the dialogue box.
My dialogue box does not terminate when I enter "-1". What could be the issue? Here is my code
let numGrade; //variable that holds number grade entry
let letter; //this variable holds grade as a letter
//this function checks whether our grade within the range
numGrade = window.prompt("Enter number grades from 0 to 120\nOr enter - 1 to end entries")
if (numGrade == -1){
return false;
}
else if(numGrade<=120 && numGrade>=0){
//calling replaceGrades function, passing a number grade to convert it to a letter grade
// store a grade letter in "final"
final = replaceGrades(numGrade)
//display a number grade and letter grade
alert("Number grade = " + numGrade + "\nLetter grade = " + final)
//this function takes in number grade as a parameter--
// and return a letter grade
function replaceGrades(grade) {
let letterGrade; //variable that returns a letter grade
//if else-if to convert number grades to letter grades{
if (grade >= 100 && grade <= 120) {
return letterGrade = "A";
} else if (grade >= 80 && grade <= 99) {
return letterGrade = "B";
} else if (grade >= 70 && grade <= 79) {
return letterGrade = "C";
} else if (grade >= 60 && grade <= 69) {
return letterGrade = "D"
} else {
return letterGrade = "F";
}
}
}
else {
numGrade = window.prompt("Enter number grades from 0 to 120\nOr enter - 1 to end entries")
}
I'm looping a prompt to ask the user to enter an integer and sort it using bubble sort method and printing it in an output. I need a button when clicked to ask the user to enter 4 numbers and output them as integers and be sorted and printed in the HTML page from the empty array I presented. I just need help understanding how to set it up because I have been trying and not getting it down right. Not an avid coder.
<!DOCTYPE html>
<html>
<head>
<title>User Input, Sort and Find!</title>
<style>
</style>
</head>
<body>
<h2>Enter 4 numbers user!</h2>
<p id="myprint"></p>
<button onclick="userInput()">Input your Numbers!</button>
<button onclick="searchInput()">Find an inputed number in your array </button>
<script>
var numbers = [];
function userInput() {
for(var i = 0; i < 4; i++){
numbers.push(prompt("Enter a number 1 at a time, from 1-9 until prompts ask you 4 times:"));
if (numbers[i] = NaN) {
alert("Enter a number!");
} else if( numbers[i] % 1 == 0) {
alert("Enter a whole number!")
}
}
}
//Sort the array and print numbers in inner html
function bubbleSort(numbers) {
var length = numbers.length;
for (var i = (length - 1); i >= 0; i--) {
for (var j = (length - i); j > 0; j--) {
if (numbers[j] < numbers[j - 1]) {
var nmbr = numbers[j];
numbers[j] = numbers[j - 1];
numbers[j - 1] = nmbr;
}
}
}
}
function searchInput() {
}
document.getElementById("myprint").innerHTML = "Your numbers are" + numbers;
</script>
</body>
</html>
I have looked at your code and there seems to be a few errors I can spot.
for(var i = 0; i < 4; i++){
numbers.push(prompt("Enter a number 1 at a time, from 1-9 until prompts ask you 4 times:"));
if (numbers[i] = NaN) { // this is the wrong logic ...
alert("Enter a number!");
} else if( numbers[i] % 1 == 0) { **// this is not correct because your basically saying every integer number is not a whole number.**
alert("Enter a whole number!")
}
}
}
The algorithm I have provided below for your loop that prompts the user considers all the scenarios that could go wrong and deal with them, at least this should give you a good base to move onto whatever you wish to do with it next.
for(var i = 0; i < 4; i++){
var num = prompt("Enter a number 1 at a time, from 1-9 until prompts ask you 4 times:");
if (isNaN(num)) {
alert("Enter a number!");
--i; // reset the counter for amount of numbers entered
}
if( !isNaN(num)) {
if( num % 1 != 0){
alert("Enter a whole number!")
--i; // reset the counter for amount of numbers entered
}else{
numbers.push(num);
}
}
}
I'm programming a method in JavaScript/JQuery which converts the value an user enters in an inputbox. The meaning is to make this input regional aware.
The functionality contains removing zeros at the beginning, placing thousand seperators and a decimal separator.
In this use case is the , symbol a thousand separator and the . dot the decimal separator
For example following input gets converted in following output.
12300 => 12,300.00
100 => 100.00
1023.456 => 1,023.456
Now There is still a problem with numbers, less than 100.
For example following input is malformed:
1 => 1,.00
2.05 => .05
20 => 20,.00
25.65 => .65
When I don't enter a decimal value in the input box, I get an unneeded thousand separator. When I enter a decimal value, I lose my content before the decimal separator.
The code:
$("#queryInstructedAmountFrom").change(function(){
var amount = $("#queryInstructedAmountFrom").val();
amount = removeZeros(amount);
var nonFractions = amount.match(/.{1,3}/g);
if(nonFractions == null) {
nonFractions = [];
nonFractions.push(amount);
}
var splittedValues = amount.split(/[,.]/);
amount = "";
if(splittedValues.length == 1) {
amount += splittedValues[0];
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if(firstIndex != 0) {
var firstNumbers = amount.substr(0, firstIndex);
amount = amount.substr(firstIndex);
nonFractions = amount.match(/.{1,3}/g);
if(nonFractions == null) {
nonFractions = [];
nonFractions.push(amount);
}
amount = "";
amount += firstNumbers;
amount += thousandSeparator;
} else {
amount = "";
}
for(var i=0 ; i < nonFractions.length ; i++) {
amount += nonFractions[i];
if(i < (nonFractions.length - 1) && nonFractions.length != 1){
amount += thousandSeparator;
}
}
amount += decimalSeparator;
amount += "00";
} else {
for(var i=0 ; i < splittedValues.length - 1 ; i++) {
amount += splittedValues[i];
}
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if(firstIndex == 0) {
nonFractions = amount.match(/.{1,3}/g);
}
if(firstIndex >= 1 && nonFractions != null) {
var firstNumbers = amount.substr(0, firstIndex);
amount = amount.substr(firstIndex);
nonFractions = amount.match(/.{1,3}/g);
if(nonFractions != null) {
amount = "";
amount += firstNumbers;
amount += thousandSeparator;
} else {
nonFractions = [];
nonFractions.push(amount);
}
} else {
amount = "";
}
for(var i=0 ; i < nonFractions.length ; i++) {
amount += nonFractions[i];
if(i < (nonFractions.length - 1) && nonFractions.length != 1){
amount += thousandSeparator;
}
}
amount += decimalSeparator;
amount += splittedValues[splittedValues.length -1];
}
$("#queryInstructedAmountFrom").val(amount);
});
});
function removeZeros(amount) {
while (amount.charAt(0) === '0') {
amount = amount.substr(1);
}
if(amount.length == 0){
amount = "0";
}
return amount;
}
What is going wrong?
What is going wrong?
I'd say almost everything. You have very unclear, messy code, I hardly following your logic, but you have several critical logic mistakes in code, for example:
1
1 is converted to 1,.00 because:
var splittedValues = amount.split(/[,.]/);
creates array with single element ['1']
var firstIndex = amount.length % 3;
1%3 == 1, so you're going into if condition, where amount += thousandSeparator; appends thousand separator, but you should add separator only if you have something after that
2
2.05 is wrong, because it goes into this branch:
var firstNumbers = amount.substr(0, firstIndex); // stores '2' into firstNumbers
amount = amount.substr(firstIndex); // sets amount to empty string
later, nonFractions is null:
nonFractions = [];
nonFractions.push(amount);
but firstNumbers is not used at all, ie its value is lost
3
also, you have:
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if (firstIndex == 0) {
nonFractions = amount.match(/.{1,3}/g);
}
what is the sense of nonFractions re-init?
probably there are more errors and edge cases where this code fails, I suggest you to use library (like in other answers) or if you want to have your own code, here is simple version you can use:
$(document).ready(function() {
$("#queryInstructedAmountFrom").change(function() {
var val = parseFloat(('0' + $("#queryInstructedAmountFrom").val()).replace(/,/g, '')); // convert original text value into float
val = ('' + (Math.round(val * 100.0) / 100.0)).split('.', 2);
if (val.length < 2) val[1] = '00'; // handle fractional part
else while (val[1].length < 2) val[1] += '0';
var t = 0;
while ((val[0].length - t) > 3) { // append thousand separators
val[0] = val[0].substr(0, val[0].length - t - 3) + ',' + val[0].substr(val[0].length - t - 3);
t += 4;
}
$("#queryInstructedAmountFrom").val(val[0] + '.' + val[1]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="queryInstructedAmountFrom">
Why don't you use jQuery-Mask-Plugin?
<input type="text" id="money" />
and just invoke the plugin:
$('#money').mask('000.000.000.000.000,00', {reverse: true});
Plunker: https://plnkr.co/edit/PY7ihpS3Amtzeya9c6KN?p=preview
Refer to the below code updated.
$(document).ready(function() {
$("#queryInstructedAmountFrom").change(function() {
var amount = $("#queryInstructedAmountFrom").val();
amount = removeZeros(amount);
// format amount using 'ThousandFormattedValue' function
amount = ThousandFormattedValue(amount);
$("#queryInstructedAmountFrom").val(amount);
});
});
function removeZeros(amount) {
while (amount.charAt(0) === '0') {
amount = amount.substr(1);
}
if (amount.length == 0) {
amount = "0";
}
return amount;
}
function ThousandFormattedValue(iValue) {
// declaring variables and initializing the values
var numberArray, integerPart, reversedInteger, IntegerConstruction = "",
lengthOfInteger, iStart = 0;
// splitting number at decimal point by converting the number to string
numberArray = iValue.toString().split(".");
// get the integer part
integerPart = numberArray[0];
// get the length of the number
lengthOfInteger = integerPart.length;
// if no decimal part is present then add 00 after decimal point
if (numberArray[1] === undefined) {
numberArray.push("00");
}
/* split the integer part of number to individual digits and reverse the number
["4" , "3" , "2" , "1"] - after split
["1" , "2" , "3" , "4"] - after reverse
"1234" - after join
*/
reversedInteger = integerPart.split("").reverse().join("");
// loop through the string to add commas in between
while (iStart + 3 < lengthOfInteger) {
// get substring of very 3 digits and add "," at the end
IntegerConstruction += (reversedInteger.substr(iStart, 3) + ",");
// increase counter for next 3 digits
iStart += 3;
}
// after adding the commas add the remaining digits
IntegerConstruction += reversedInteger.substr(iStart, 3);
/* now split the constructed string and reverse the array followed by joining to get the formatted number
["1" , "2" , "3" , "," ,"4"] - after split
["4" , "," , "3" , "2" , "1"] - after reverse
"4,321" - after join
*/
numberArray[0] = IntegerConstruction.split("").reverse().join("");
// return the string as Integer part concatinated with decimal part
return numberArray.join(".");
}