Skip to content

Instantly share code, notes, and snippets.

@shenqihui
Last active January 13, 2021 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shenqihui/2af9ccfa71777d68c3b7350700b34dea to your computer and use it in GitHub Desktop.
Save shenqihui/2af9ccfa71777d68c3b7350700b34dea to your computer and use it in GitHub Desktop.
遍历对象,将数字精确化
import NP from 'number-precision';
import _ from 'lodash';
function eachAttrFormatFloat(formatElem) {
if (formatElem instanceof FormData) {
return formatElem;
}
if ('number' === typeof formatElem) {
if (_.isInteger(formatElem)) {
return formatElem;
}
const match = `${formatElem}`.match(/\.(\d+)/);
// 小数点后有大于8位(不包含8)就不要
if (match && match[1] && match[1].length && 8 < match[1].length) {
return NP.strip(formatElem);
}
// 总体长度超过16(不包含16)也不要了
if (16 < `${formatElem}`.length) {
return NP.strip(formatElem);
}
return formatElem;
}
if (_.isArray(formatElem)) {
return _.map(formatElem, (elem) => {
return eachAttrFormatFloat(elem);
});
}
if (_.isObject(formatElem)) {
const newObj = {};
_.each(_.entries(formatElem), ([k, v]) => {
newObj[k] = eachAttrFormatFloat(v);
});
return newObj;
}
return formatElem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment