简体   繁体   English

如何使用 JavaScript 从字符串中提取十进制数

[英]How to extract decimal number from string using JavaScript

I want to extract decimal number 265.12 or 0.0 from alphanumeric string (say amount) having value $265.12+ or $265.12- or $0.0+ or $0.0- and use it apply struts logic tag in jsp .我想从具有价值$265.12+$265.12-$0.0+$0.0-字母数字字符串(例如金额)中提取十进制数265.120.0并使用它在jsp应用 struts 逻辑标记。 Not sure how to extract number maybe with help of JavaScript .不确定如何在JavaScript帮助下提取数字。

You can use regex like this,你可以像这样使用正则表达式,

Live Demo现场演示

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

Without error checks, following will do:没有错误检查,以下将执行:

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

123123.098 123123.098

您可能对这个用于格式化货币的库感兴趣http://josscrowcroft.github.com/accounting.js/

Try this also,也试试这个

<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();">

A more elegant solution and also a method to avoid the 0.7700000004 javascript math do this:一个更优雅的解决方案,也是一种避免0.7700000004 javascript 数学的方法,这样做:

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

The result will always be the exact number of decimals.结果将始终是精确的小数位数。 Also a prototype for easier use也是一个更容易使用的prototype

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

so now just 15.6655.getDecimals() ==> 6655所以现在只是15.6655.getDecimals() ==> 6655

use :采用 :

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

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

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