分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

js格式化数字

发布时间:2023-09-06 01:14责任编辑:董明明关键词:js
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>格式化数字</title></head><body><script type="text/javascript">/**方法一 不加千分位(整数部分最大15位,小数为最多4位)object --文本框对象n --保留的小数位*/function fmoney(object,n){ ???// ^-?[0-9]+\.?[0-9]*$ 验证浮点数 ???var num = ?object.value; ???var start = num.indexOf(‘-‘); ???if(start == 0){ ???????num = num.substring(1,15); ???}else{ ???????num = num.substring(0,15); ???} ???num = parseFloat((num + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; ??????if (isNaN(num) || ((num + "").replace(/\s/g, "")) == "") { ???????object.value = ""; ???????return; ???} ???n = n > 0 && n <= 20 ? n : 2; ??????var l = num.split(".")[0].split("").reverse(),r = num.split(".")[1],t = ""; ??????for(var i = 0; i < l.length; i ++ ){ ????????//t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : ""); //加千分位 ???????t += l[i]; ??????} ??????if(start == 0){ ???????object.value = "-"+t.split("").reverse().join("") + "." + r; ???}else{ ???????object.value = t.split("").reverse().join("") + "." + r; ???}} ??/**方法二 加千分位 (整数部分最大15位)object --文本框对象n --保留的小数位*/function simpleFormat(object,n){ ???var num = object.value; ???num = num.substring(0,15); ???num = parseFloat((num + "").replace(/[^\d\.-]/g, "")).toFixed(n)+""; ??????if (isNaN(num) || ((num + "").replace(/\s/g, "")) == "") { ???????object.value = ""; ???????return; ???} ???object.value = num; ???var value = num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") ?????object.value = value;}function rmoney(s){ ?????return parseFloat(s.replace(/[^\d\.-]/g, "")); ??}</script><input type="text" id="11" style="width:200px" onblur=‘fmoney(this,4)‘/><input type="button" value="还原" onclick="r11()"><br><input type="text" id="33" style="width:200px" onblur=‘simpleFormat(this,4)‘/><input type="button" value="还原" onclick="r33()"><script type="text/javascript">function r11(){ ???var value = document.getElementById("11").value; ???alert(rmoney(value));}function r33(){ ???var value = document.getElementById("33").value; ???alert(rmoney(value));}</script></body></html>

js格式化数字

原文地址:http://www.cnblogs.com/bunuo/p/7611195.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved