正如你已經收集,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
會在它到達時停止(返回數字直到那一點),但仍然更清晰。
參見:
可以共享HTML –
'Number.parseLocale'是'undefined'在Chrome中。 –
您可以使用'parseInt'或'parseFloat' –