1.控制,只能輸入多少位小數
/**
* 對輸入金額進行校驗
* obj 輸入框物件
* 比如在input元素中,寫onkeyup="moneyvalidate(this,6)"
*/ function moneyvalidate(obj,decimal)/g,".");//只保留第乙個.清除多餘的
obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
if(decimal)).*$");
obj.value = obj.value.replace(reg,'$1$2.$3');
}}
2.保留小數,並向上進一位
/**
* 向上保留小數(只要目標小數字後有有效數字就進1,保證計算後的數值一定不小於原數值)
* 返回的結果,並保留fix為小數
* 比如upfixed(13.451,2)=13.46,upfixed(12,2)=12.00
* @param num
* @param fix
* @returns
*/function upfixed(num, fix) `;
return '0' + '.'+(new array(fix + 1).join('0'));
}// num為原數字,fix是保留的小數字數
let result = '0';
if (number(num) && fix > 0) else if (!/\./.test(num)) `;
result = num + '.'+(new array(fix + 1).join('0'));
} else `;
num = num + (new array(fix + 1).join('0'));
// var reg = new regexp(`-?\\d*\\.\\d}`);
var reg = new regexp("-?\\d*\\.\\d");
let floorstr = reg.exec(num)[0];
if (+floorstr >= +num) else 1`;
var floornumber = number(floorstr) + number( ('0.'+(new array(fix).join('0'))+'1'));
var point = /\./.test(floornumber + '') ? '' : '.'
// var floorstr2 = floornumber + point + `$`;
var floorstr2 = floornumber + point + (new array(fix + 1).join('0'));
result = reg.exec(floorstr2)[0];}}
}return result;
}
3.保留多少位小數,向下取
/**
* 向下保留小數(目標小數字後的數字直接捨棄,保證計算後的數值一定不大於原數值)
* 返回的結果,並保留fix為小數
* 比如downfixed(13.456,2)=13.45,upfixed(12,2)=12.00
* @param num
* @param fix
* @returns
*/function downfixed (num, fix)
// num為原數字,fix是保留的小數字數
var result = '0';
if (number(num) && fix > 0) else if (!/\./.test(num)) `;
result = num + '.'+(new array(fix + 1).join('0'));
} else `;
num = num + (new array(fix + 1).join('0'));
// var reg = new regexp(`-?\\d*.\\d}`);
var reg = new regexp("-?\\d*.\\d");
result = reg.exec(num)[0];}}
return result;
}
一些JS小方法
1.補0 例如時間上的 function repairzero val console.log repairzero 5 052.獲取當天日期是週幾 let now newdate let ww 星期 日一二三四五六 now.getday console.log ww 3.獲取指定區間隨機數 con...
js 小技巧和小方法
1.字串首字母大寫 var str xiamgfafsfsfdsf fdsfsfsf str str.substring 0,1 touppercase str.substring 1 console.log str xiamgfafsfsfdsf fdsfsfsf 2.建立乙個隨機的id func...
常用小方法
region 將字串轉換為陣列 public static string getstrarray string str endregion region 刪除最後結尾的乙個逗號 刪除最後結尾的乙個逗號 public static string dellastcomma string str endr...