您的位置:首页 > Web前端 > JavaScript

js 将数值显示为金额

2015-08-11 19:25 531 查看

项目中常遇到要将数值显示为金额。例如: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;"/> //用来保存真正的数值

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: