简体   繁体   中英

Need to convert string into number

I have a number 10,000.00 and I want to check if it is greater than 0.

function chkgrt(num)
{
    if(num>0){
        return true;
    }
    else
        return false;
}

chkgrt('10,000.00')

It always returns false . I wonder why it is returning false even though I have passed 10000 which is greater than 0.

Following gives me false since you are checking a string against 0

chkgrt('10,000.00')
false

I parse it into float as you have .00 in it, then it works

chkgrt(parseFloat('10,000.00'.replace(',','')))
true

You can modify your function as below

function chkgrt(num){
    num = num.replace(',',"");
    if(num > 0){
        return true;
    }
    else
        return false;
}

Always pass as string

It depends on how are you passing the number. If you are passing 10000 or 10000.00 to your chkgrt() function it will return true. But if you pass 10,000.00 it will return a syntax error. In order to pass 10,000.00 as the number in your function you need to parse your input using the following code :

var newNum = num.replace(',', '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM