If condition for comparing integer and float does not working - javascript

I am using one If condition in javascript ,
var iid = "c_poqty_"+itemid;
var calculatedQuantity = document.getElementById(iid).value;
if(! isNaN(actualQuantity)) {
if(actualQuantity >= calculatedQuantity) {
return true;
} else {
alert("You must enter the order qty same or greater than the calculated PO Qty");
document.getElementById(iid).focus();
return false;
}
} else {
alert("Please Enter valid number");
document.getElementById(iid).focus();
return false;
}
Here, calculatedQuantity is always in float and while actualQuantity can be integer,
I have one testcase:
calculatedQuantity = 1.0
actualQuantity = 1
Appreciate for your help!

Actually, I suspect they're both strings. Certainly calculatedQty is, as you've retrieved it from the value of an input field, and the value property's value is always a string. Use parseInt and/or parseFloat so you're comparing numbers rather than strings.
Consider:
console.log("1.0" > "1"); // "true"
console.log(1.0 > 1); // "false"

Related

Find the output using typeof function

I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function

How to get Inifinite Values for textbox

how do I change that the user is able to key in the value from 0- infinite?
Because it only allows the user to key in from 0-9 at this moment.
function validate() {
var values = document.getElementById("digit").value;
if (/^[0-9]$/.test(values) == false) {
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero";
return false;
}
return true;
}
Use typeof and the urnary operator + to check if its an number and greater equal then 0
function validate() {
var value = document.getElementById("digit").value;
if (!(!isNaN(+value) && value >= 0)) {
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero";
return false;
}
document.getElementById("numbers").innerHTML = "";
return true;
}
<input onkeyup="validate()" value="" id="digit" />
<p id="numbers"></p>
Your Regular expression is looking for one and only one digit between the start and end of the string.
Try /^[0-9]$+/.
The + means 'At least one, up to an infinity of' whatever it's stuck too.
Use the native method Number.isInteger() to check if the last character is a number. If not, slice it.
function validate(el) {
var lastChar = Number(el.value.slice(-1));
if (!Number.isInteger(lastChar)) {
el.value = el.value.substring(0, el.value.length - 1);
};
}
<input type="text" oninput="validate(this)">

Javascript Eval() thinks first value is a function

I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)

check if input form value (int) is less than expected

My question is about validating a form. I am doing a validation of two fields, one of them receives the value in decimal, example ($ 500.00), is already with mask.
In this field that receives the value, it can not be less than 300.00.
If it is smaller 300.00, a message will appear saying the value has to be greater than 300.00.
Summary: The validation checks that it is empty, but does not check if the (number) int is less than $ 300
I'm using it this way (there's more code, in short):
function valid_simulation(form1) {
if (form1.valor.value == ' ') {
alert("value is not valid");
return false;
}
if (form1.valor.value <= 300) {
alert("value is not valid");
return false;
}
}
Thanks for any help.
Your basic concept is correct: set the message when the if statement test is falsy. Something like the following:
function showFormError(message) {
$("#alertBox").text(message)
}
if (isInvalid) { showFormError("We have a problem.") }
If the dollar mark is the issue, You can split it and validate.
var userInput = $("#inputData").val();
if(userInput.includes("$")) {
var splitArray = userInput.split("$");
if (typeof splitArray[1] && parseFloat(splitArray[1]) < 300){
alert("Amount Not valid");
}
}

Javascript user input validation

My exercise is to force a user to type a number and check that it is less than 100. I think I've done this well but there is another case I don't know how to do. If the user does not type any number in the space, the program should show something like "you must type a number". How should I write the code?
var number=prompt('enter a number');
if (number<100){
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
}else if(number>100){
document.write('type again');
}
You can determine if the users input is a valid number by using the isNaN function. I have also validated the blank character for you, as shown below.
var isValid = !isNaN(number) && number !== "";
Full snippet:
var number = prompt('enter a number');
number = number.replace(/\s/g, "");
var isValid = !isNaN(number) && number !== "";
if (isValid) {
if (number<100) {
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
} else if(number>100) {
document.write('type again');
}
} else {
document.write("Looks like you didn't enter a valid number");
}
https://jsfiddle.net/ezgn5cv5/
var number = null;
while (number !== 0 && !number || number >= 100) {
number = parseInt(prompt('Enter a number, less than 100'));
}
document.write(
number +
' is less than 100 by ' +
(100 - number)
);
This puts us in a loop for whether or not the number is a valid integer (I assumed that's what you wanted, but you could change this to float or something else), and under 100. Only when the user's input is valid will it go to the line to output.
The second condition for the while loop is !number. This basically tests for falsy conditions, such as NaN or null. If parseInt() can't figure out what the user typed in for a number, it will return NaN. And, of course, we initialized the number variable to null.
The first condition for while is number !== 0 is actually required because of the second condition which tests for falsy. 0 is falsy, but 0 is a valid number less than 100, so we need to make sure that we let 0 be valid. Conditionals like these short circuit. That means that they are processed from left to right, and any condition failing the test will immediately bypass the conditional block of code below. If number is 0, we know that the whole condition is false and we can move on.
The third condition simply ensures we're under 100 by re-prompting if we're not.
Also, I should note that document.write() has some issues. It's better to select an element on the page and set its text.
Remove all spaces .replace(/\s/g, "").
Detect if user input a number using parseFloat() if you want to allow
user to input decimal numbers like 5.254 or only integers using
parseInt() like 5.
Then detect if number > 100 or number < 100.
See this example:
var number = prompt('enter a number');
number = number.replace(/\s/g, ""); //remove all spaces
if (number != "") { // if not empty
if (parseFloat(number) == number) { // if decimal/integer number
if (number < 100) {
newnumber = 100 - number;
document.write(number + ' is less than 100 by ' + newnumber);
} else if (number > 100) {
//number = prompt('enter a number');
document.write('type again');
}
} else {
//number = prompt('enter a number');
document.write('you must type a number');
}
} else { // if empty input
//number = prompt('enter a number');
document.write('shouldn\'t be empty');
}

Categories

Resources