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;"/> //用来保存真正的数值
相关文章推荐
- jstack命令
- JavaScript 的核心,闭包和作用域
- QML中使用JavaScript
- jsp自定义标签
- JavaScript-html标题滚动效果
- ajax dataType:"json"问题
- JavaScript闭包详解
- 如何将json数据传入到Highcharts中的data中
- JS设置cookie、读取cookie、删除cookie
- JavaScript基础学习之-JavaScript权威指南--第八章函数属性方法构造函数
- 有意思的字符串反转(JavaScript)
- js小数点后保留几位方法:toFixed
- js小数点后保留几位方法:toFixed
- javascript要点整理(一)
- js模块化编程(二):AMD规范
- js模块化编程(一):模块的写法
- js中2个等号与3个等号的区别
- 闲来js基础-----2
- JavaScript基础学习之-javascript权威指南--第八章函数闭包
- JS获取当前时间的方法