2014-01-30 69 views
0

我有如下JS方法,如果數字是正數,則變量percentageValue返回正確,但如果數字是負數,則返回NaN。我不知道如何解決它。Javascript函數Number.parseLocale返回NaN當有負數

function Test() { 
    debugger; 
    var catLength= $("[id$=lblCat]").length; 
    for (var i = 0; i < catLength- 1; i++) { 
     var categoryValue = Number.parseLocale($("[id$=" + i + "_lblCat]")[0].title); 
     var percentageValue = Number.parseLocale(($("[id$=" + i + "_txtPercentage]")[0].value).replace("%", "")); 

    } 
} 
+0

可以共享HTML –

+0

'Number.parseLocale'是'undefined'在Chrome中。 –

+1

您可以使用'parseInt'或'parseFloat' –

回答

1

這就是你試圖做

var num = $("[id$=" + i + "_txtPercentage]")[0].value).replace("%", ""); 
//lets say num is 3500 
num.toLocaleString();//returns for me 3 500 

文檔:Number.prototype.toLocaleString()

+1

這似乎是工作正常!!!!。我需要更多的時間與其他場景。 – user1301587

1

您可以使用標準parseInt

var a = parseInt("-2"); 
var b = parseInt("2"); 

http://jsfiddle.net/AV4rB/

標準編號對象沒有parseLocale方法:

Object.getOwnPropertyNames(Number) 
["length", "name", "arguments", "caller", "prototype", "MAX_VALUE", "MIN_VALUE", "NaN", "NEGATIVE_INFINITY", "POSITIVE_INFINITY", "isFinite", "isNaN"] 
+3

'parseInt'不可能根據名稱做任何'parseLocale'。具體來說,'parseInt(「1,200」,10)''是'1',而在我的語言環境(英國英語)中它實際上是1200.在其他某些語言環境中,「1200」是1200,而在我的語言環境中,它是1和2/10 。因此需要一個語言環境特定的解析函數。 –

0

試試這個

function Test() { 
debugger; 
    var catLength= $("[id$=lblCat]").length; 
    for (var i = 0; i < catLength- 1; i++) { 
     var categoryValue = parseFloat($("[id$=" + i + "_lblCat]")[0].title, 2); 
     var percentageValue = parseFloat(($("[id$=" + i + "_txtPercentage]")[0].value, 2).replace("%", "")); 

    } 
} 
+0

'parseFloat'不太可能根據名稱做任何'parseLocale'。具體來說,'parseFloat(「1,200」)''是'1',而在我的語言環境中(英國英語)它實際上是1200.在其他某些語言環境中,「1200」是1200,而在我的語言環境中則是1和2/10是什麼'parseFloat'返回)。因此需要一個語言環境特定的解析函數。 –

+0

我嘗試parFloat耳鼻涕,但不幸它不工作。 – user1301587

1

正如你已經收集,JavaScript的Number沒有parseLocale功能。你需要回到你正在使用的任何庫上來。

如果你需要創建你自己的,你可以做到這一點是這樣的:

(function() { 
    var thousandsep, decimalsep, rexFindThousands, rexFindDecimal; 

    thousandsep = (1200).toLocaleString().replace(/\d/g, '').substring(0, 1); 
    decimalsep = (1.2).toLocaleString().repalce(/\d/g, '').substring(0, 1); 
    if (!thousandsep) { 
     // Big assumption here 
     thousandsep = decimalsep === "." ? "," : "."; 
    } 
    rexFindThousands = new RegExp("\\" + thousandsep, "g"); 
    rexFindDecimals = new RegExp("\\" + decimalsep, "g"); 

    Number.prototype.parseLocaleString = function(str) { 
     str = String(str).replace(rexFindThousands, '').replace(rexFindDecimals, '.'); 
     return parseFloat(str); 
    }; 
})(); 

嘗試檢測的特定區域,千小數點分隔符,再添加了一個功能Number完全刪除千位分隔符,並用.parseFloat使用的那個)替換小數點分隔符,然後返回使用parseFloat解析的結果。

但我會強調toLocaleString的輸出是依賴於實現的。小數點的東西很可能會起作用,但我不知道toLocaleString返回一個包含千位分隔符的字符串的可靠程度,因此上面是回退的假設。

另請注意,如果您正在解析的字符串中有一個%,則在解析該字符串之前,您需要將其刪除。 parseFloat會在它到達時停止(返回數字直到那一點),但仍然更清晰。

參見: