保留指定小数位数js函数封装
不用正则保留指定小数位数
- 函数入参定义,
- num:需要处理的数据
- len:保留小数位数,默认2位
- 判断类型,统一转字符串处理
- 空值return 空字符串
- numStr.replace(/[^0-9.]/g,‘’) // 限制值只能为0-9和字符‘.’
- let isDecimalIndex = numStr.indexOf(‘.’) // 判断存不存在小数位
- 不存在小数的话,就直接转number后转string,吐出去,目的是为了把不正确的格式return出去
- 存在小数的话,需要截取整数位和小数位,然后再处理小数位中的无效字符,并截取指定传进来的执行长度
export function KeepDecimals(num:string|number,len =2 ){
let numStr = typeof(num) == "number" ? `${num}` : num
if(!numStr)return '';
numStr=numStr.replace(/[^0-9.]/g,'')
let isDecimalIndex = numStr.indexOf('.')
if(isDecimalIndex === -1)return `${Number(numStr)}`
let integer = numStr.slice(0,isDecimalIndex)
let Decimals = numStr.slice(isDecimalIndex+1)
Decimals=Decimals.replace(/[^0-9]/g,'').slice(0,len)
return `${Number(integer)}.${Decimals || ''}`
}