54

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?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

17 Answers17

49

Like this:

if (!isNaN(value) && value.toString().indexOf('.') != -1)
{
    alert('this is a numeric value and I\'m sure it is a float.');
}​
MikeL
  • 5,385
  • 42
  • 41
Nelson
  • 49,283
  • 8
  • 68
  • 81
  • 2
    Well, 9.0 could be perfectly accepted as an integer for most people logics, not saying this is the exact answer, but it can get the job done. – Nelson Sep 17 '12 at 22:29
  • 36
    -1 as only works for some countries. Many use periods as thousand separators or not at all. Most of Europe uses commas for floating point values. – Keith Jul 23 '15 at 08:04
  • 1
    It doesn't works if the value contains two or more points('.'). – SAI GIRI CHARY AOUSULA Jun 14 '18 at 06:47
  • 2
    @Keith: Don't browser implementations of javascript work the same across all countries? That is, don't they all treat a period as the decimal separator? Regardless, strings with thousands separators, whether they are commas or periods, will not be treated a valid numbers by javascript interpreters anyway. – kloddant Apr 17 '19 at 13:54
  • 1
    @kloddant JS does, user input does not. If you have a JS string that might contain a number then you _might_ not have this problem. If you have a JS number you can use `toString` to get invariant formatting or `toLocale​String` to get a specific format - so if you can ensure that numbers in strings used `toString` this answer is fine. However, if you have user input the test in this answer will only find the invariant formatting, but users may expect either thousand separators or their cultural decimal indicators to work. – Keith Apr 17 '19 at 14:30
42

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
Flimm
  • 136,138
  • 45
  • 251
  • 267
Mangiucugna
  • 1,732
  • 1
  • 14
  • 23
  • 11
    @Mangiucugna I did. And it has problems. Have you tried, for example, feeding `"3.2.1.release"` to it? Guess what happens... This is a very problematic glitch of *parseXXX*. Also, you answered the conversion part, but not the testing part - you never test for the value being float, but for being any kind of number (which might as well be fine since technically every `Number` is a float in JS) – Powerslave Aug 09 '13 at 07:30
  • 7
    `parseFloat('2016-03-01')` returns true. Huh? That's not a number, that's a date! – Michael Mar 02 '16 at 22:17
  • 1
    "If parseFloat encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters." So `parseFloat('1asd2sd%.')` turns to be a float too – dnaranjo Mar 08 '16 at 15:26
  • 1
    That's not quite right. parseFloat("123blah456") comes out as the number 123, which is a valid number. – Sarhanis Jan 22 '18 at 23:38
  • I've edited the answer to make it clear `parseFloat` treats a string like "123blabla" as a number. – Flimm Oct 02 '20 at 08:43
17

Following functions also check for format. E.g. JavaScript native parseInt and parseFloat functions also parse strings containing non numeric characters, and functions above have consequences of this.

// For example, following code will work
var n = parseInt('123asd');
n == 123

These functions will return false for such string.

function isFloat(val) {
    var floatRegex = /^-?\d+(?:[.,]\d*?)?$/;
    if (!floatRegex.test(val))
        return false;

    val = parseFloat(val);
    if (isNaN(val))
        return false;
    return true;
}

function isInt(val) {
    var intRegex = /^-?\d+$/;
    if (!intRegex.test(val))
        return false;

    var intVal = parseInt(val, 10);
    return parseFloat(val) == intVal && !isNaN(intVal);
}
Nikola Radosavljević
  • 6,871
  • 32
  • 44
  • Nikola, is "," valid float separator? I think only dot is. – Dragomir Ivanov Oct 19 '15 at 10:46
  • 1
    @DragomirIvanov, we are discussing user input. Number formats depend on users locale. E.g. in Germany, you would use comma as decimal places separator, and period as thousands separator. You are right about language syntax though. Programming languages mostly use period for decimal separators, but this was not original question. In a way, this is an issue with regexes above, as there is no strict implementation of locales, but support for both formats in one place. I think this would be beyond scope of this question as it requires whole article. – Nikola Radosavljević Oct 20 '15 at 11:12
  • 1
    This `floatRegex` will return true for `1231.` or `87.`. I think the following is better: `/^-?\d+([.,]?\d+)?$/`. It returns true for integers too BTW. – haffla Nov 14 '17 at 14:10
  • 2
    Be careful about numbers with exponent. If you want to correctly process tohse - you can use eg.: `/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/` Credit: https://www.regular-expressions.info/floatingpoint.html – Jan Apr 12 '18 at 15:28
9

To check if a string is an integer or a float

function isFloat(n) {
    return parseFloat(n.match(/^-?\d*(\.\d+)?$/))>0;
}

//alert(isFloat("3.444"));
Pang
  • 9,564
  • 146
  • 81
  • 122
Yasas Rangika
  • 359
  • 4
  • 8
6

In my case a very simple regex did the trick.

I needed to validate an user's input whether the input is a valid monetary value. I simply used-

/^[0-9]+(\.)?[0-9]*$/.test(number)

everything between // is the Regular Expression.

/^ means the match starts from the beginning of the word and $/ means the match ends with the word. If you think the word can not start with the letter 0 then the expression would be like [1-9][0-9]*

[0-9]+ means the word must start with at least one number.

Note: * means zero or more, + means one or more and ? means one or none.

Up to here the expression is /^[1-9][0-9]*$/ and this would validate only the integer numbers.

To test for a period (.) in the number we need to use \. with the expression. . is a special character which matches everything, \. will only match the period.

Finally another character class [0-9]* would match with zero or more digits.

Test Cases

/^[0-9]+(\.)?[0-9]$/.test("21.38a") // ==> false
/^[0-9]+(\.)?[0-9]$/.test("21.38") // ==> true
/^[0-9]+(\.)?[0-9]$/.test("y2781.68") // ==> false
/^[0-9]+(\.)?[0-9]$/.test("2781r.68") // ==> false
maksbd19
  • 3,785
  • 28
  • 37
5
Number.prototype.isFloat = function() {
    return (this % 1 != 0);
}

Then you can

var floatValue = parseFloat("2.13");
var nonFloatValue = parseFloat("11");

console.log(floatValue.isFloat()); // will output true
console.log(nonFloatValue.isFloat()); // will output false

Values like 2.00 cannot really be considered float in JS, or rather every number is a float in JS.


EDIT: Forgot to mention that extending the prototypes of built-in types is considered a bad parctice (for a good reason) and its use is discouraged in production environments. You could still implement this check as a plain function
Powerslave
  • 1,408
  • 15
  • 16
  • this does not work with large floating points. ( Number.MAX_VALUE * Math.random() ) % 1 != 0 // gives off false. This is because module will return 0 on large floating points. – Mient-jan Stelling Dec 31 '14 at 13:03
  • 1
    @Mient-janStelling That's a technical limitation of floats. They have precision problems and, roughly speaking, no number will be technically float above a certain threshold. POC: `Math.round(Number.MAX_VALUE - 0.001) === Number.MAX_VALUE - 0.001` (in fact, you could substitute the module method above with this "rounded value equation" check) – Powerslave Dec 31 '14 at 14:12
  • You're correct, extending the prototype of a built-in type is considered bad practise. – Flimm Oct 02 '20 at 09:03
4

Use This:

var isNumber = /^\d+\.\d+$/.test(value);
Adithya Sai
  • 1,592
  • 2
  • 19
  • 33
3
function checkFloat(value) {
    let parsed = Number.parseFloat(value);
    return (!Number.isNaN(parsed)) && (!Number.isInteger(parsed))
}
prmph
  • 7,616
  • 11
  • 37
  • 46
2

To check if a string is a float (avoid int values)

function isFloat(n) {
   if( n.match(/^-?\d*(\.\d+)?$/) && !isNaN(parseFloat(n)) && (n%1!=0) )
      return true;
   return false;
}

var nonfloat = isFloat('12'); //will return false
var nonfloat = isFloat('12.34abc'); //will return false
var float = isFloat('12.34'); //will return true
rodrigomelo
  • 59
  • 1
  • 1
  • 3
1

Only if value is passed in as a string can we fully determine if it uses a decimal point or not. Because 1.0 (as a number) results in 1 though "1.0" (as a string) results in "1.0" exactly the same. And from there we can find if it contains a decimal point, .. So we need to pass the argument value as a string.

The following will work if value is a string

if ( value.indexOf('.') > -1 ) { // value is a floating point

}

value.toString() will not turn 1.0 to "1.0" (rather, it would simply turn it to 1) so passing by string is the best alternative because it maintains all of its characters.

If you do not wish to use a string, then there is no way of capturing 1.0 as a floating-point value. Use the following if you want to test of a number is a floating point value:

The following will not work for 1.0, 1.00, etc.

if ( value >>> 0 !== x ) { // value is a floating point

}

Note: You should also check for !isNaN(value) (I left that out to focus on the changes).

David G
  • 94,763
  • 41
  • 167
  • 253
1

If you need to check if value is int or float:

function isFloatOrInt(n) {
    return !isNaN(n) && n.toString().match(/^-?\d*(\.\d+)?$/);
}
Andron
  • 6,413
  • 4
  • 43
  • 56
1

This function returns the numeric value of a string regardless if int or float

function getNumericVal(str) {
    if(isNaN(str)) return;
    try {return parseFloat(str);} 
    catch(e) {return parseInt(str);}
}
Dinesh Kanivu
  • 2,551
  • 1
  • 23
  • 55
0

use this jquery code

    <script>
    $(document).ready(function () {
        $(".allow_only_float").keypress(function (e) {

            if (e.which != 46 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                e.preventDefault();//return false;
            }
            var avg = $('#<%=txtAverage.ClientID%>').val();
            var idx = avg.indexOf(".");
            if (idx > -1 && e.which == 46) {
                e.preventDefault();//return false;
            }
        });
    });
    </script>
<body>
    <input type='text' class='allow_only_float'>
</body>
R.Akhlaghi
  • 729
  • 1
  • 12
  • 23
0
function isFloat(inputString) {
    const parsed = parseFloat(inputString);

    return !isNaN(parsed) && parsed.toString() === inputString;
}

isFloat('.4') // false
isFloat('1.4') // true
isFloat('1.') // false
isFloat('1') // true
isFloat('asd') // false
isFloat('123asd') // false
Georgi Vatsov
  • 428
  • 6
  • 10
  • fails with: isFloat('0.0') // false – Manfred May 19 '21 at 21:48
  • @Manfred i think you just need to add positive ched as a second step and not in this one. `const isPositive = (value) => (parseFloat(value) > 0)` and than `if (isFloat(v) && isPositive(v)) {}` – Tim Kozak Nov 21 '22 at 03:46
0

In may cases this is enough

function isFloat(n) {
    return (typeof n === 'number' && !isNaN(n) && n !== Infinity && n !== -Infinity) || (typeof n === 'string' && /^\-?[0-9]+(e[0-9]+)?(\.[0-9]+)?$/.test(n));
}
-1

straight forward:

if (parseFloat(value).toString() === value.toString()) {
    ...
}
user2846569
  • 2,752
  • 2
  • 23
  • 24
  • 3
    clever, but fails for cases where there are more than one valid representation of the same number, e.g. `parseFloat('0.0000000000000001').toString()` yields `1e-16` – Michael Mar 02 '16 at 22:19
  • 2
    Also parseFloat('1234567.890').toString() == 1234567.89 – igo Sep 26 '17 at 07:00
-3
if (!isNaN(value) && String(value).includes('.')) {
    alert("it's a float");
    let newFloatValue = parseFloat(value)
}
TheDon
  • 11
  • 4