Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string is a float?

I am passing in a parameter called value. I'd like to know if value is a float. So far, I have the following:

if (!isNaN(value)) {     alert('this is a numeric value but not sure if it is a float.'); } 

How do I go one step further and convert the string to something that can evaluate to a float?

like image 279
Nate Pet Avatar asked Sep 17 '12 21:09

Nate Pet


People also ask

How do I check if a string is float or int?

To check if a string is an integer or a float:Use the str. isdigit() method to check if every character in the string is a digit. If the method returns True , the string is an integer. If the method returns False , the string is a floating-point number.

Can a string be a float?

We pass the value of the 'string' variable as the parameters of the float() method. Create a variable for storing the result. If the defined string is a float number, it returns 'True,' and if the defined string is not a float value, it returns 'False.

Is a string or float?

A STRING is literally a "string" of characters. A letter, a sentence, anything that is not a "value" .. A FLOAT is just a number with a decimal. As an INT is a whole number (no decimal) - a FLOAT is basically like an INT but with a decimal.


2 Answers

Like this:

if (!isNaN(value) && value.toString().indexOf('.') != -1) {     alert('this is a numeric value and I\'m sure it is a float.'); }​ 
like image 169
Nelson Avatar answered Oct 04 '22 12:10

Nelson


You can use the parseFloat function.

If the value passed begins with what looks like a float, the function returns the value converted to a float, otherwise it will return NaN.

Something like:

function beginsWithFloat(val) {   val = parseFloat(val);   return ! isNaN(val); } console.log(beginsWithFloat("blabla")); // shows false console.log(beginsWithFloat("123blabla")); // shows true
like image 42
Mangiucugna Avatar answered Oct 04 '22 11:10

Mangiucugna