Finding variable types from a string - javascript

Pardon if this question has already been answered however I'm struggling to find the any answers to it.
I'm looking to see if I can convert variable types to a string in the code below.
input = prompt('Type something please', 'your input here')
alert(input + ' is a ' + typeof input)
i.e. if the user were to type 1 typeof would return number, or if the user were to enter true it would return a boolean

You can run the input through a series of parseInt, parseFloat and
parseBool
functions.
Whenever you get a valid result, return it.
Something similar to:
if (parseInt(input) != NaN) {
return "int"
}
if (parseFloat(input) != NaN) {
return "float"
}

Generally, all inputs per your example will return a string careless of what they entered or intended to enter. We could however build a few logics to check if what they entered is; Strings (Alphabets only) or an integer (numbers only) or any other ones per a few other logics you could base your checks on.
One of the quickest ways to check if an input contains a number or not;
isNaN(input) // this returns true if the variable does NOT contain a valid number
eg.
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
you could try regex (which is not always ideal but works)
var input = "123";
if(num.match(/^-{0,1}\d+$/)){
//return true if positive or negative
}else if(num.match(/^\d+\.\d+$/)){
//return true if float
}else{
// return false neither worked
}
You could also use the (typeof input) but this will be more convenient if your user is going to enter an expected set of entries
var input = true;
alert(typeof input);
// This eg will return bolean
Let me know if this helps.

Related

JavaScript - Check if input is a number

I'm facing the following (basic) problem: I want to check if an input from an HTML-input field is not greater than 5 or not a number. If this is given the function should return true. Otherwise (so if greater than 5 or a number) it should resturn false. The validation if the number is not greater than 5 works fine so far but when I add the typeof-argument this one doesn't works.
This is my code so far, thanks in advance!
function isValidStart(start) {
if (start.trim().length > 5 || typeof(start) === 'number') {
return false
}
return true
An Element.value (input, select, textarea etc) will always be a String.
Test if a single-digit integer range is used can be achieved with a small Regex and RegExp.prototype.test().
Test an integer of length 5
const isValidStart = v => /^\d{1,5}$/.test(v); // or use [0-5]
console.log(isValidStart("1")) // true
console.log(isValidStart("55555")) // true
console.log(isValidStart(2)) // true
console.log(isValidStart("a12")) // false
You don't even have to care if a value is a String or Number.
Single integer:
to match single digits from range 1 to 5:
const isValidStart = v => /^[1-5]$/.test(v); // or use [0-5]
console.log(isValidStart("1")) // true
console.log(isValidStart(2)) // true
console.log(isValidStart("a")) // false
console.log(isValidStart("6")) // false
You can use the Number.isFinite() function to check if a variable is a finite number, which in your use case should do the Job.
let intVar = 2;
Number.isFinite(intVar);
$true
However it looks like your start variable is not actually a number as you can't call .trim() on a number. So this if statement will never return True.
You should typecast your variable. https://www.w3schools.com/js/js_type_conversion.asp
let reg = new RegExp(/^\d{0,5}$/);
console.log(reg.test('1'));
console.log(reg.test('12'));
console.log(reg.test('123'));
console.log(reg.test('1234'));
console.log(reg.test('12345'));
console.log(reg.test('string'));
console.log(reg.test('124var123'));

Javascript: Ensure Input is Numbers Only

I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.

isFinite of space giving true value

I am trying to validate a price field. I was trying this:
var productId = document.getElementById("productId");
var productName = document.getElementById("productName");
var productPrice = document.getElementById("price");
alert(isFinite(productPrice.value));
if(isNaN(productPrice.value)||!isFinite(productPrice.value)){
error = document.getElementById("priceError");
error.innerHTML = "Please enter correct value";
productPrice.style.border="thin solid red";
}else{
error = document.getElementById("priceError");
error.innerHTML = "";
}
The line alert is giving me true when the input is space/ multiple spaces only.
This is my HTML page.
<td>Price</td>
<td><input type = "text" id = "price" size = "14"/></td>
Thanks
Why this happens i cant say, but this code should solve the problem
isFinite(parseFloat(" ")) // false
// because -->
parseFloat(" "); // => result NaN
// tested in Chrome 27+ on Win7
in the MDN refernce of isNaN here
it says
isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN
Update:
in the Reference of isFinite found Here it states that isFinite only returns false if the argument is:
NaN
positive infinity, (Number.POSITIVE_INFINITY)
negative infinity (Number.NEGATIVE_INFINITY)
In any other Case it returns true. (like Paul S mentioned)
Now i Think i got all loose ends, and in that course learned something. :)
with window.isFinite, you must be aware of the issues that window.isNaN suffers from when coercing types.
window.IsNaN Summary
Determines whether a value is NaN or not. Be careful, this function is
broken. You may be interested in ECMAScript 6 Number.isNaN.
Examples
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN(true); // false
isNaN(null); // false
isNaN(37); // false
// strings
isNaN("37"); // false: "37" is converted to the number 37 which is not NaN
isNaN("37.37"); // false: "37.37" is converted to the number 37.37 which is not NaN
isNaN(""); // false: the empty string is converted to 0 which is not NaN
isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN
// This is a false positive and the reason why isNaN is not entirely reliable
isNaN("blabla") // true: "blabla" is converted to a number. Parsing this as a number fails and returns NaN
In ECMAScript 6 there are new methods Number.isNaN and Number.isFinite that address these issues. (of course these are not available in many browsers)
Number.isFinite is equivalent to
function isFinite(number) {
return typeof number === "number" && window.isFinite(number);
}
So as a solution, you would need to consider something like this (cross-browser).
Note: this solution will still allow you to enter hexadecimal or scientific notations, "0xA", "1e10"
Javascript
function isFinite(number) {
return typeof number === "number" && window.isFinite(number);
}
function trim(string) {
return string.replace(/^\s+|\s+$/g, "");
}
var price = document.getElementById("price");
price.onchange = function (e) {
var evt = e || window.event,
target = evt.target || evt.srcElement,
value = trim(target.value) || "NaN",
number = +value;
console.log("number:", number);
console.log("isFinite:", isFinite(number));
}
On jsfiddle
You could do it using reqular expression.
Try this.
function validatePrice() {
var el = document.getElementById('price');
if (
el.value.length < 14 &&
/^ *\+?\d+ *$/.test( el.value )
)
{
return true;
}
return false;
}
This function checks if the input is positive integer. I didnt know if you want floated values also.
If you do, switch the regex to this /^ *+?\d+((.|,)\d+)? *$/

What causes isNaN to malfunction? [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 9 years ago.
I'm simply trying to evaluate if an input is a number, and figured isNaN would be the best way to go. However, this causes unreliable results. For instance, using the following method:
function isNumerical(value) {
var isNum = !isNaN(value);
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
on these values:
isNumerical(123)); // => numerical
isNumerical("123")); // => numerical
isNumerical(null)); // => numerical
isNumerical(false)); // => numerical
isNumerical(true)); // => numerical
isNumerical()); // => not numerical
shown in this fiddle: http://jsfiddle.net/4nm7r/1
Why doesn't isNaN always work for me?
isNaN returns true if the value passed is not a number(NaN)(or if it cannot be converted to a number, so, null, true and false will be converted to 0), otherwise it returns false. In your case, you have to remove the ! before the function call!
It is very easy to understand the behaviour of your script. isNaN simply checks if a value can be converted to an int. To do this, you have just to multiply or divide it by 1, or subtract or add 0. In your case, if you do, inside your function, alert(value * 1); you will see that all those passed values will be replaced by a number(0, 1, 123) except for undefined, whose numerical value is NaN.
You can't compare any value to NaN because it will never return false(even NaN === NaN), I think that's because NaN is dynamically generated... But I'm not sure.
Anyway you can fix your code by simply doing this:
function isNumerical(value) {
var isNum = !isNaN(value / 1); //this will force the conversion to NaN or a number
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
Your ternary statement is backward, if !isNaN() returns true you want to say "numerical"
return isNum ? "not numerical" : "<mark>numerical</mark>";
should be:
return isNum ? "<mark>numerical</mark>" : "not numerical";
See updated fiddle:
http://jsfiddle.net/4nm7r/1/
Now that you already fixed the reversed logic pointed out on other answers, use parseFloat to get rid of the false positives for true, false and null:
var isNum = !isNaN(parseFloat(value));
Just keep in mind the following kinds of outputs from parseFloat:
parseFloat("200$"); // 200
parseFloat("200,100"); // 200
parseFloat("200 foo"); // 200
parseFloat("$200"); // NaN
(i.e, if the string starts with a number, parseFloat will extract the first numeric part it can find)
I suggest you use additional checks:
function isNumerical(value) {
var isNum = !isNaN(value) && value !== null && value !== undefined;
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
If you would like treat strings like 123 like not numerical than you should add one more check:
var isNum = !isNaN(value) && value !== null && value !== undefined && (typeof value === 'number');

Understanding underscore's implementation of isNaN

Taken from the underscore.js source:
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
Why did they do it this way? Is the above implementation equivalent to:
_.isNaN = function(obj) {
return obj !== obj;
};
If it is, why the "more complicated" version? If it is not, what are the behavioural differences?
_.isNaN(new Number(NaN)) returns true.
And that's by design.
var n = new Number(NaN);
console.log(_.isNaN(n), n!==n); // logs true, false
The host environment (e.g. web-browser environment) may introduce other values that aren't equal to themselves. The _.isNumber(obj) part makes sure that the input is a Number value, so that _.isNaN only returns true if the NaN value is passed.
If + is given before of any value with no preceding value to + , JavaScript engine will try to convert that variable to Number.If it is valid it will give you the Number else it will return NaN. For example
+ "1" // is equal to integer value 1
+ "a1" // will be NaN because "a1" is not a valid number
In above case
+"a1" != "a1" // true, so this is not a number, one case is satisfied
+"1" == "1" // true, so it is number
Another simple case would be, why the below expression give this output
console.log("Why I am " + typeof + "");
// returns "Why I am number"
Because +"" is 0.
If you want to check whether it is a number or not you could use the below function
function isNumber(a){
/* first method : */ return (+a == a);
/* second method : */ return (+(+a) >= 0);
// And so many other exists
}
Someone correct me if I am wrong somewhere..
I found one case for _.isNaN
It shows different result with the native one if you pass there an object
_.isNaN({}) => false
//but
isNaN({}) => true

Categories

Resources