Last active
January 13, 2021 02:30
-
-
Save shenqihui/2af9ccfa71777d68c3b7350700b34dea to your computer and use it in GitHub Desktop.
遍历对象,将数字精确化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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