function formatting(num) {
//非空判断
if (num == "" || num == null || num == undefined || num.indexOf("-") == 0 || isNaN(num)) {
return 0;
}
//以.开头,补0
if (num.indexOf(".") == 0) {
num = "0" + num;
}
//得到小数点的位置
var number = num.indexOf(".");
//以点结束
if (number = num.length - 1) {
num=num.substr(0, num.length - 1)
}
//小于1的小数
if (num.indexOf("0.") == 0) {//如果是以0.开头
if (num.length > 2) {
//截取小数点都的数据
var str2 = num.substring(number + 1);
//判断小数
if (str2.length <= 4) {
return num;
} else {
var str3 = str2.substr(0, 4);
var str4 = "0." + str3
return str4;
}
} else {
return 0;
}
} else {//大于等于1的数
if (number == -1) {//没有小数点
if (num.length <= 10) {
return num;
} else {
var str5 = num.substr(0, 10);
return str5;
}
} else {//有小数点
//小数点前的数据
var str6 = num.substring(0, number);
//小数点后的数据
var str7 = num.substring(number + 1);
if (str6.length > 10) {
var str8 = num.substr(0, 10);
return str8;
}
if (str7.length > 4) {
var str9 = str7.substr(0, 4);
var str10 = str6 + "." + str9;
return str10;
}
return num;
}
}
}
改进版:
function myformat(num, integerlength, decimalslength) {
var return0=parseFloat(0).toFixed(decimalslength);
if (integerlength == null || integerlength == "" || integerlength == undefined) {
integerlength = 10;
}
if (decimalslength == null || decimalslength == "" || decimalslength == undefined) {
decimalslength = 2;
}
if(num==""||num==null||num==0||isNaN(num)||num==undefined||num<0){
return return0;
}else{
var number = num.indexOf(".");
//以.开头
if(number==-1){//没有小数点
return parseFloat(num.length>integerlength?num.substr(0,integerlength):num).toFixed(decimalslength);
}else if(number==0){//以点开头
num=num.substr(number+1).length>decimalslength?num.substr(number+1).substr(0,decimalslength):num.substr(number+1);
return "0."+num;
}else if(number==num.length-1){//以点结尾
num=parseFloat(num.substr(0, num.length - 1).length>integerlength?num.substr(0,integerlength):num.substr(0, num.length - 1)).toFixed(decimalslength);
return num;
}else {//正常小数
var num1=num.substring(0,number);
var num2=num.substring(number+1);
if(num1.length>integerlength){
return parseFloat(num1.substr(0,integerlength)).toFixed(decimalslength);
}else{
num2=num2.length>decimalslength?num2.substr(0,decimalslength):num2;
return num1+"."+num2;
}
}
}
}