Do not count invalid guesses (not numbers or out of range) - javascript

So I am at the last bit of my assessment and have figured out everything I believe. However, the only thing that I am having trouble with is omitting out of range numbers within the tracked guesses. I was able to omit (0 and negative) numbers but I am not sure how to go about omitting numbers that go over the user inputted maximum number. For example, if the user states the maximum number should be 55 and they guess 65. I don't want the guess of 65 to be included in my guesses array. Here is the code I have currently to omit 0 and negative numbers. Any suggestions on alterations to it to omit guesses above the maximum number? Thank you in advance.
if(guess == num) {
message.innerHTML = "BOOM! You got it! It took you " + guessAmount.length + " tries to get it and the numbers you guessed were " + guessAmount.filter(val => val > 0);

Update the filter condition like so:
.filter(val => val > 0 && val <= MAX_GUESS)

Related

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.

Can anyone explain this process with converting decimal numbers to Binary

I have looked around the internet for a way to convert decimal numbers into binary numbers. and i found this piece of code in some forum.
var number = prompt("Type a number!") //Asks user to input a number
var converted = []; // creates an array with nothing in it
while(number>=1) { //While the number the user typed is over or equal to 1 its shoud loop
converted.unshift(number%2); // takes the "number" and see if you can divid it by 2 and if theres any rest it puts a "1" otherwise "0"
number = Math.floor(number/2); // Divides the number by 2, then starts over again
}
console.log(converted)
I'm not understanding everything completely, so i made some comments of what i think the pieces of code do. But anyone that can explain in more detail? or is the way i think the code does correct?
This code is based on a technique for converting decimal numbers to binary.
If I take a decimal number. I divide it by two and get the remainder which will either be 0 or 1. Once you divide 57 all the way down to 0. You get the binary number for example:
57 / 2 = 28 r 1; 28 / 2 = 14 r 0; 14 / 2 = 7 r 0; 7 / 2 = 3 r 1; 3 / 2 = 1 r 1; 1 / 2 = 0 r 1;
The remainders are the binary number. Sorry if it's a bit hard to read. I definitely recommend writing it out on paper. Read from the last remainder to the first, the remainders look like this: 111001
Reverse it to make it correct. array.unshift() can do this or you could use array.push() then array.reverse() after the while loop. Unshift() is probably a better approach.
57 in decimal is equal to 111001, which you can check.
BTW, this algorithm works for other bases, as long you are converting from decimal. Or at least as far as I know.
I hope this helped.
It seems like you've got the gist of it down.
Let's start with a random number:
6 === 110b
Now let's see what the above method does:
The number is geq than 1, hence, let's add the last bit of the number to the output
6%2 === 0 //output [0]
the number we're working with after dividing the number by two, which is essentially just bit-shifting the whole thing to the right is now 11b (from the original 110b). 11b === 3, as you'd expect.
You can alternatively think of number % 2 as a bit-wise AND operation (number & 1):
110
& 1
-----
0
The rest of the loop simply carries the same operation out as long as needed: find the last bit of the current state, add it to the output, shift the current state.

Validating a text field containing a float is a valid percentage value?

I have a form text field that has a KeyUp event. On KeyUp I'm ignoring anthing but numbers, the period, backspace, delete and cursor keys. So, the only thing in the field can be a number or period.
I need to verify these things (number will become a % not over 100.00%):
-The text field string is a valid number (which should always be true unless someone puts two '.'s in).
-The text field string has a max of 2 decimal places
-If the text field string has a decimal point, it has something after (1 or 2 decimal places, not just a period at the end)
-The number is not larger than 100 (<= 100)
examples (what I need to verify):
95 is true (valid, decimal places not required)
95. is false (don't need a '.' with no decimal place after)
95.0 is true
95.00 is true
95.000 is false (3 decimal places not valid) 100 is true
101.01 is false (over 100)
101 is false (over 100)
I've seen some things that do several pieces of that list, but I'm not smart enough to modify the regex to get exactly what I need. Thanks for any help!
Some people will suggest regexes, but I think a small function is better suited for such a validation:
function validate(x) {
var parts = x.split(".");
if (typeof parts[1] == "string" && (parts[1].length == 0 || parts[1].length > 2))
return false;
var n = parseFloat(x);
if (isNaN(n))
return false;
if (n < 0 || n > 100)
return false;
return true;
}
console.log(validate("95"));
console.log(validate("95."));
console.log(validate("95.0"));
console.log(validate("95.00"));
console.log(validate("95.000"));
console.log(validate("101.01"));
console.log(validate("101"));
Live example
try this expression: the 100% is a special case of a more generic pattern
var re = /^((0|[1-9]\d?)(\.\d{1,2})?|100(\.00?)?)$/;
explanation
(0|[1-9]\d?) allows numbers from 0 to 99
(\.\d{1,2})? allows a dot with 1 or 2 digits after
| otherwise
100 accept 100
(\.00?)? with optional 0 or 00
Edit:
I tried this jsfiddle demo http://jsfiddle.net/pCDVn/1/ and it's working... look at the console
You could limit the length of your field to 5, check that the value can be cast to a number, and then verify that the number is between 0 and 100. You won't be able to enter 100.00, but why would you need to?
Also, here's a fiddle for testing. One note, if you really care about validating "95." as false, you'll have to add extra validation for that. However, I'd advise against this requirement, because it is still represents a valid percentage and won't affect the outcome of calculations.

javascript: trying to validate a number that has to be 4 digits to see if x<100 (ie 0100)

i hate asking for help as i would rather figure things for myself, or learn from what others have posted or already asked and solved. as such this is my first post on here!
This is either really really simple and im over complicating things or im going about it the wrong way. ive been searching everywhere for over 2 hours now. im not exactly a noob at js but i am still sort of new,i would say learning, ameteur?? anywho....
what i am trying to do:
so i have a number input box <input type="number" maxlength="4" .../> where a user will enter a 4 digit number (needs to be 4 digits) from 100 to 8000. so obviously 100 to 999 would be 0100 - 0999.
no problem so far, i can just use a string to pass the variable through as 4 digits.
the problem i have is that i need to add certain conditions to validate the input. one condition is bugging me. this is what i have so far:
(var x is already set to the form and number input box)
if (x=="" || isNaN(x) || x.length!== 4 && x< 0100 || x>8000)
{alert(please enter the correct amount!}
else {run rest of function}
so they all work execpt for:x<0100
if the user enters 99 it flags up because it is not 4 digits and if they enter 0099 it accepts it and runs the rest of the function code.
i just need it to alert for any amount from 0001 to 0099.
i found another post, How to make 8 digit number in javascript? , sort of relevant but the guy just wants to output a number padded with zeros. i think one of the solutions (code below) may be of use to me but as i am rather tired, brain frazzled and new i cant solve it:
var i = (100).toPrecision(8).split('.').reverse().join('');
i would start by editing it to:
var i = (x).toPrecision(4).split('.').reverse().join('');
(but would this only work if they typed 99 not 0099...if ya see what i mean)
i think it would be like a reverse of the code (split 0099 to 99.00) , and then the statement would be: if(.... && i<==99 || ....) but idk how to write it in JS...
ok so do ya see how this is messing with me mind, being a semi/quarterly noob and all!!
sorry its not formatted correctly and so long, i havent grasped how to use the code functions...
and thanks for your patience in reading this (if you got this far hehe).
THANKS IN ADVANCE
Slappy-x
The number 0100 will be treated as octal value (which is 64 in decimal).
I think you would do fine by just comparing against strings:
x < "0100" || x > "8000"
Otherwise you have to convert the x into a number and compare it against 100:
+x < 100 || +x > 8000
(actually you don't have to explicitly convert x but it does not hurt either and makes it clearer which data types you are comparing)
Update: And you have to replace && with || as far as I can see.
To check if x is between 0001 and 0099, you can do this
if (x.match(/00([1-9][0-9]|0[1-9])/))
Try a combination of these methods.
You want to check that your number is actually a number first (i.e. doesn't contain letters, etc.). Do this by calling this method to confirm your number is a valid numeric value.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Once confirmed that you're dealing with a number, you can pad it (if necessary) like this:
function pad(num, size) {
var s = "000" + num;
return s.substr(s.length-size);
}
To work with padded numbers, you actually have to convert the value to a string.

comparing two floats to see if they're both negative, or both positive

Hay guys, i have 2 floats, which both comes from input boxes.
I need to compare these 2 floats, if one is negative and one is positive thrown an error. If they're both positive, or both negative, thats fine.
Any ideas?
Thanks
Multiply them together.
If the answer is positive then they are both the same sign.
If the answer is negative then they are of opposite sign.
If the answer is zero (within some value to take care of rounding error) then one or both are zero and you'll have to check them individually. You'll then have to decide whether 0 to be treated as positive or negative in your scenario.
Although detection of the sign of the product can be done, it's not what you are interested in. Especially if you're going to use it on large volumes of floats (eg to detect a zero crossing in a time stream).
The simplest way is to exactly express what you ask for: is the sign of a equal to the sign of b?
function samesign( a, b ) {
var aPositive = a >= 0;
var bPositive = b >= 0;
return aPositive == bPositive;
}
Or shorter:
function samesign( a, b ) { return (a>=0) == (b>=0); }
Just do something like:
if float1*float2<0
Error
function isSameSign(a,b){
var r = a*b;
return (r >= 0)
}

Categories