前端框架中常见的公共方法汇总(二):时间格式处理/数字格式处理

时间格式处理

// 把时间的分秒值去掉
export const formatTM = item => {
  if (item) {
    let newItem = item.replace(':00.0', '')
    if (newItem.indexOf('.') > 0) {
      newItem = newItem.substr(0, 16)
    }
    return newItem
  } else {
    return ''
  }
}

// 把时间的时分秒去掉
export const formatDay = item => {
  if (item) {
    const newItem = moment(item).format('yyyy-MM-DD')
    return newItem
  } else {
    return ''
  }
}

// 把空值返回-
export const formatX = item => {
  if (item) {
    return item
  } else {
    return '-'
  }
}

// 把空值返回空格
export const formatSpace = item => {
  if (item) {
    return item
  } else {
    return ' '
  }
}

数字小数位处理

// 判断是否为数值  true 数值类型 false 其他
function isNum(val) {
  // 先判定是否为number
  if (typeof val !== 'number') {
    return false
  }
  if (!isNaN(val)) {
    return true
  } else {
    return false
  }
}
// 判断是否为数值  true 数值类型 false 其他
function formatNum(val, digit) {
  // 异常值判断
  if (val === null || isNaN(val) || val === undefined || val === '' || val === ' ') return '-'
  // 数值 或 字符串数值
  val = parseFloat(val).toFixed(digit)

  // 删除尾部的‘0’
  if (val.endsWith('0')) {
    val = val.substring(0, val.lastIndexOf('0'))
  }

  // 删除尾部的‘.’
  if (val.endsWith('.')) {
    val = val.substring(0, val.lastIndexOf('.'))
  }
  return val
}
// 保留一位小数
export const formatDrp = item => {
  return formatNum(item, 1)
}
// 保留两位小数
export const formatRz = item => {
  return formatNum(item, 2)
}
//  保留3位有效数字
export const formatW = item => {
  const dec = 2 // 保留n位有效数值 (n-1)
  const newItem = parseFloat(item)
  let num = ''
  if (isNum(newItem) || parseFloat(newItem) === item) {
    const toExponential = newItem.toExponential(dec) // (转成科学计数法)
    num = Number(toExponential) // 转成普通数字类型
  }
  return num
}

你可能感兴趣的:(vue,javascript,前端,vue,vue.js,javascript,js)