从文本元素中获取小数

问题描述 投票:1回答:4

例如,我有一个HTML元素(“总付款”),其中包含文本:“支付100.00英镑”。

我设法从中获得数字100,如下所示:

function getPaymentAmount(paymentAmount) {
    var stringTotal = $("#paymentBtn").text();
    var extractIntFromTotal = stringTotal.match(/\d+/)[0];
    return extractIntFromTotal;
}

但是,我想取回十进制的100.00。我尝试添加到索引上,但这似乎不起作用。谁能帮忙吗?我对javascript非常陌生。

谢谢:)

javascript jquery html dom
4个回答
0
投票

关于使用split()然后使用pop()

function getPaymentAmount(paymentAmount) {
    var stringTotal = 'Pay £100.00'; 
    var extractIntFromTotal = stringTotal.split('£').pop();
    return extractIntFromTotal;
}

console.log(getPaymentAmount());

0
投票

阅读问题的两句之间,看来实际的目标是从字符串中获取全价,包括十进制值。

最简单的方法是修改正则表达式以包括小数:

function getPaymentAmount(paymentAmount) {
  var extractIntFromTotal = paymentAmount.match(/\d+\.\d{2}?/)[0];
  return extractIntFromTotal;
}

var amt = getPaymentAmount('Pay £100.00');
console.log(amt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

-1
投票

var text = "Pay £100.00";
var no = text.split("£")[1];
console.log(Math.floor(no));

-1
投票

尝试一下

    var stringTotal = $("#paymentBtn").text();
    var number = Number(stringTotal.replace(/[^0-9.-]+/g,""));
    console.log(number);
© www.soinside.com 2019 - 2024. All rights reserved.