zoukankan      html  css  js  c++  java
  • js 将数值显示为金额

    项目中常遇到要将数值显示为金额。例如:3000 => $3,000.00

    function formateMoney(number, places, symbol, thousand, decimal) {
        number = number || 0;
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        symbol = symbol !== undefined ? symbol : "$";
        thousand = thousand || ",";
        decimal = decimal || ".";
        var negative = number < 0 ? "-" : "",
            i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
            j = (j = i.length) > 3 ? j % 3 : 0;
        return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(d{3})(?=d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    }
    
    function getSelectPos(obj) {
        var esrc = document.getElementById(obj);
        if (esrc == null) {
            esrc = event.srcElement;
        }
        var rtextRange = esrc.createTextRange();
        rtextRange.moveStart('character', esrc.value.length);
        rtextRange.collapse(true);
        rtextRange.select();
    }

    具体用法:

    $("#tbPrice").focus(function () {
            var price = $("#Price").val();
            $(this).val(price);
            getSelectPos("tbPrice");
     });
    
        $("#tbPrice").blur(function () {
            var value = $(this).val();
            if (!isNaN(value) && value != "") {
                var price = parseFloat(value);
                var formattedPrice = formateMoney(price, 2, "");
                $("#Price").val(price.toFixed(2));
                $(this).val(formattedPrice);
            }
            else {
                $("#Price").val("");
            }
        });

    Html部分为:

    <input type="text" id="tbPrice" name="tbPrice"/> //用来显示金额
    <input type="text" id="Price" name="Price" style="display:none;"/> //用来保存真正的数值
  • 相关阅读:
    八数码难题 (codevs 1225)题解
    小木棍 (codevs 3498)题解
    sliding windows (poj 2823) 题解
    集合删数 (vijos 1545) 题解
    合并果子 (codevs 1063) 题解
    等价表达式 (codevs 1107)题解
    生理周期 (poj 1006) 题解
    区间 (vijos 1439) 题解
    区间覆盖问题 题解
    种树 (codevs 1653) 题解
  • 原文地址:https://www.cnblogs.com/cherryzhou/p/4722106.html
Copyright © 2011-2022 走看看