how to extract decimal number from string using javascript

前端 未结 6 1922
春和景丽
春和景丽 2021-01-12 11:02

I want to extract decimal number 265.12 or 0.0 from alphanumeric string (say amount) having value $265.12+ or $265.12- or

相关标签:
6条回答
  • 2021-01-12 11:13

    Without error checks, following will do:

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

    123123.098

    0 讨论(0)
  • 2021-01-12 11:13

    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();">
    
    0 讨论(0)
  • 2021-01-12 11:16

    You might be interested in this library for formatting money http://josscrowcroft.github.com/accounting.js/

    0 讨论(0)
  • 2021-01-12 11:29

    You can use regex like this,

    Live Demo

    var amount = "$265.12+";
    var doublenumber = Number(amount.replace(/[^0-9\.]+/g,""));
    
    0 讨论(0)
  • 2021-01-12 11:32

    A more elegant solution and also a method to avoid the 0.7700000004 javascript math do this:

    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

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

    so now just 15.6655.getDecimals() ==> 6655

    0 讨论(0)
  • 2021-01-12 11:34

    use :

    var str = parseFloat("$265.12".match(/[\d\.]+/))
    alert(str % 1); => 0.12000000000000455
    
    0 讨论(0)
提交回复
热议问题