简体   繁体   English

需要将字符串转换为数字

[英]Need to convert string into number

I have a number 10,000.00 and I want to check if it is greater than 0. 我有一个数字10,000.00,我想检查它是否大于0。

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

chkgrt('10,000.00') chkgrt('10,000.00')

It always returns false . 它总是返回false I wonder why it is returning false even though I have passed 10000 which is greater than 0. 我想知道为什么即使我通过了大于0的10000,它仍返回false

Following gives me false since you are checking a string against 0 以下为我提供了错误信息,因为您正在针对0检查字符串

chkgrt('10,000.00')
false

I parse it into float as you have .00 in it, then it works 我将其解析为float,因为其中有.00,然后它起作用了

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. 如果将10000或10000.00传递给chkgrt()函数,它将返回true。 But if you pass 10,000.00 it will return a syntax error. 但是,如果您通过10,000.00,它将返回语法错误。 In order to pass 10,000.00 as the number in your function you need to parse your input using the following code : 为了在函数中传递10,000.00作为数字,您需要使用以下代码来解析输入:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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