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

Posted 前端阿多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端框架中常见的公共方法汇总:时间格式处理/数字格式处理相关的知识,希望对你有一定的参考价值。

时间格式处理

// 把时间的分秒值去掉
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项目中常见的公共方法汇总:通用校验处理

Vue项目中常见的公共方法汇总:通用校验处理

java读取excel时间格式出现数字怎么处理

excel中使用VALUE函数的方法步骤

leetcode 最常见的前端基础算法面试题汇总