用于页面上格式化数字字符串,此代码为工作时所需,留作笔记,比较常用。
/**
* author: xg君
* 描述: 格式化数字字符串,格式化小数位
* obj为需要格式的对象(例如:input标签)
* maxLength 为最大小数位长度
* minLength 为最小小数位长度
*/
function toFloat(id,maxLength,minLength){
var htmlVal = $("#"+id).val();
var index = htmlVal.indexOf(".");
var result = "";
if(index > ){
htmlVal = htmlVal.replaceAll("0+?$","");
var len = htmlVal.substring(index+).length;
if(len > ){
if(len > ){
result = Number(htmlVal).toFixed(maxLength);
result = reToFloat(result,maxLength,minLength);
}else{
result = Number(htmlVal).toFixed(len);
result = result.replaceAll("0+?$","");
}
}else {
result = Number(htmlVal).toFixed(minLength);
}
}else {
result = Number(htmlVal).toFixed(minLength); }
$("#"+id).val(result);
} function reToFloat(htmlVal,maxLength,minLength){
var index = htmlVal.indexOf(".");
var result = "";
if(index > ){
htmlVal = htmlVal.replaceAll("0+?$","");
var len = htmlVal.substring(index+).length;
if(len > ){
if(len > ){
result = Number(htmlVal).toFixed(maxLength);
}else{
result = Number(htmlVal).toFixed(len);
result = result.replaceAll("0+?$","");
}
}else {
result = Number(htmlVal).toFixed(minLength);
}
}else {
result = Number(htmlVal).toFixed(minLength); }
return result; }