2012-05-02 116 views
2

我想提取從字母數字串的十進制數265.120.0來提取字符串十進制數(說量)具有值$265.12+$265.12-$0.0+$0.0-並使用它適用支柱邏輯標籤在jsp。不知道如何在javascript的幫助下提取數字。如何使用javascript

回答

11

您可以使用正則表達式這樣,

Live Demo

var amount = "$265.12+"; 
var doublenumber = Number(amount.replace(/[^0-9\.]+/g,"")); 
2

沒有錯誤檢查,下面會做什麼:

var string = "$123123.0980soigfusofui" 
var number = parseFloat(string.match(/[\d\.]+/)) 

123123.098

0

你可能有興趣在這個庫用於格式化貨幣http://josscrowcroft.github.com/accounting.js/

+0

他怎麼能當他需要提取,不打印? –

+0

有一個名爲unformat()的方法返回數字。例如。 accounting.unformat(「$ 12,345,678.90」); // 12345678.9 – 250R

0

使用:

var str = parseFloat("$265.12".match(/[\d\.]+/)) 
alert(str % 1); => 0.12000000000000455 
0

試試這個也

<script type="text/javascript"> 
function validate(){ 
    var amount = $("#amount").val(); 
    alert(amount.split(".")[1]); 
} </script> 
</head> 
<body> 
<input type="hidden" name="amount" id="amount" value="25.50"> 
<input type="submit" onclick="validate();"> 
0

一個更優雅的解決方案,也是一個方法,以避免0.7700000004 JavaScript的數學做到這一點:

var num = 15.3354; Number(String(num).substr(String(num).indexOf('.')+1));

結果將始終是精確的小數位數。此外,使用更簡便

Number.prototype.getDecimals = function() { return Number(String(this).substr(String(this).indexOf('.')+1)); }

所以現在prototype只是15.6655.getDecimals() ==> 6655