How can I check if a string is a float?

前端 未结 14 1818
清歌不尽
清歌不尽 2020-12-23 20:21

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 num         


        
14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 20:44

    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

提交回复
热议问题