• 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;"/> //用来保存真正的数值
  • 相关阅读:
    python3.6关键字总结
    python文件操作
    基础之你容易忽略的细节
    模块一
    内置函数
    java成员变量和局部变量的区别
    java面向对象
    java数组
    java函数(方法)语法规则
    java流程控制switch
  • 原文地址:https://www.cnblogs.com/cherryzhou/p/4722106.html
Copyright © 2020-2023  润新知