前端开发在处理保留小数位数的时候遇到一个坑,保留两位有效位数,
**保留两位有效位数:**例如:1.00000567,保留成1.0000057,有效数字的两位小数(上学时候好像学过这种数字,忘了,哈哈哈)
翻了很长时间百度,没有找到直接能用的方法。。。于是自己封装了一下,记录一下,有用到的直接拿去。
先上处理方法的代码,拿去直接使用:
/*** 适合处理小数位数特别多的情况,不会丢失精度(但是直接传入字符串的数字)* @param {*} newnum 需要转化的数字(字符串)* @param {*} bitnum 需要转化为几位有效位数* @returns 需要转化为几位有效数字*/
const ToEffectiveNum = (newnum, bitnum = 2) => {if (isNaN(newnum)) {return 0;}if (newnum === 0 || newnum === '0') {return 0;}if (typeof newnum === 'number') {newnum = newnum.toString();} if (typeof newnum === 'string') {const fast = newnum.split('.')[0]; // 拿小数点前面的内容(字符串)if (Number(fast)>0) { // 如果小数点前面的内容大于0,直接返回return Number(newnum).toFixed(2)}const last = newnum.split('.')[1]; // 拿小数点后面的内容(字符串)if (!last) return Number(newnum).toFixed(2) // 如果没有小数点后面的内容,直接返回const index1 = last.split('').findIndex(item => item !== '0') // 不是0的第一个位置索引if (index1 === -1) return Number(newnum).toFixed(2) // 如果小数点后面的内容全是0,直接返回if(index1 === 0) return Number(newnum).toFixed(2) // 说明直接保留两位即可return Number(newnum).toFixed(index1+2) // 返回结果(Number类型)}
}
console.log(ToEffectiveNum('0.0000000000011745')); // 0.0000000000012
这个处理方法不会以为传入的位数太多导致精度丢失等问题(推荐)。
/**
* 可以直接数字num
* 适合处理位数不会特别多的小数
* 缺点:小数位数太多无法处理,会返回0
*/
const liangweiunm = function istownum(num) {const str = num.toString();const houmian = str.substring(str.indexOf('.')+1, str.length); // 拿小数点后面的内容(字符串)const zhuanshuzi = Number(houmian) // 转换成数字后会自动去掉开头的0const indexNew = houmian.indexOf(zhuanshuzi); // 拿到小数点后面的数字的位置const result = num.toFixed(indexNew+2);return result;
}
console.log('liangweiunm', liangweiunm(54456456));
const value = 0.0000008;
(function significantNum(value, count = 1) {let newNum = count;let value1 = parseFloat(value);let newData = value1.toFixed(newNum + 1);if (value1 === 0) {return newData;}if (parseFloat(value1.toFixed(2)) === 0) {if (parseInt(value1 * Math.pow(10, newNum)) === 0) {newNum++;return significantNum(value1, newNum);} else {newData = value1.toFixed(newNum + 1);}} else {newData = value1.toFixed(2);}console.log(newData);return newData;
}
)(value)
(这个方法目前只是处理0开头的小数,,其他的没有做判断,因为做到这里发现方案不太可行,效率太低了)
运行效果就上一个截图吧。
✨个人笔记博客✨
星月前端博客
http://blog.yhxweb.top/
✨原创不易,还希望各位大佬支持一下
👍 点赞,你的认可是我创作的动力!
⭐️ 收藏,你的青睐是我努力的方向!
✏️评论,你的意见是我进步的财富!