utils_format.js 5.66 KB
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 时间戳转化为年 月 日 时 分 秒
 * ts: 传入时间戳
 * format:返回格式,支持自定义,但参数必须与formateArr里保持一致
 */
const tsFormatTime = (timestamp, format) => {
  format = format || 'Y-M-D h:m:s'
  const formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
  let returnArr = []

  let date = new Date(timestamp)
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  returnArr.push(year, month, day, hour, minute, second)

  returnArr = returnArr.map(formatNumber)

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i])
  }
  return format
}

/**num:要转换的数值,fixed:精确几位小数 */
const decimal = (num, fixed) => {
  const pow = Math.pow(10, fixed)
  return Math.round(num * pow) / pow
}

const setPrice = price => {
  let [num, decimal] = price.toString().split('.')
  if (!decimal) decimal = '00'
  return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') + `.${decimal}`
}
// 格式化日期
const dateFormatter = str => {
  let o = new Date()
  if (str) {
    o = new Date(str)
  }
  let y = o.getFullYear()
  let m = o.getMonth() + 1
  let d = o.getDate()
  let time = y + '年' + m + '月' + d + '日'
  return time
}
/**
 * 大数字转换,将大额数字转换为万、千万、亿等
 * @param value 数字值
 */
const bigNumberTransform = value => {
  const newValue = ['', '', '']
  let fr = 1000
  let num = 3
  let text1 = ''
  let fm = 1
  while (value / fr >= 1) {
    fr *= 10
    num += 1
    // console.log('数字', value / fr, 'num:', num)
  }
  if (num <= 4) {
    // 千
    newValue[0] = parseInt(value / 1000) + ''
    newValue[1] = '千'
  } else if (num <= 8) {
    // 万
    text1 = parseInt(num - 4) / 3 > 1 ? '千万' : '万'
    // tslint:disable-next-line:no-shadowed-variable
    fm = text1 === '万' ? 10000 : 10000000
    if (value % fm === 0) {
      newValue[0] = parseInt(value / fm) + ''
    } else {
      newValue[0] = parseFloat(value / fm).toFixed(2) + ''
    }
    newValue[1] = text1
  } else if (num <= 16) {
    // 亿
    text1 = (num - 8) / 3 > 1 ? '千亿' : '亿'
    text1 = (num - 8) / 4 > 1 ? '万亿' : text1
    text1 = (num - 8) / 7 > 1 ? '千万亿' : text1
    // tslint:disable-next-line:no-shadowed-variable
    fm = 1
    if (text1 === '亿') {
      fm = 100000000
    } else if (text1 === '千亿') {
      fm = 100000000000
    } else if (text1 === '万亿') {
      fm = 1000000000000
    } else if (text1 === '千万亿') {
      fm = 1000000000000000
    }
    if (value % fm === 0) {
      newValue[0] = parseInt(value / fm) + ''
    } else {
      newValue[0] = parseFloat(value / fm).toFixed(2) + ''
    }
    newValue[1] = text1
  }
  if (value < 1000) {
    newValue[0] = value + ''
    newValue[1] = ''
  }
  return newValue.join('')
}
const numberFixedDigit = num => {
  // 固定两位小数
  num = num.match(/^\d*(\.?\d{0,2})/g)[0] || ''
  return num
  // this.$nextTick(() => {
  //   this.number = e.target.value
  // })
}
// 除以100保留两位小数点
const divideByHundred = str => {
  let floatVal = parseFloat(str)
  if (isNaN(floatVal)) {
    return 0
  }
  floatVal = Math.round(str * 100) / 10000
  let strVal = floatVal.toString()
  let searchVal = strVal.indexOf('.')
  if (searchVal < 0) {
    searchVal = strVal.length
    strVal += '.'
  }
  while (strVal.length <= searchVal + 2) {
    strVal += '0'
  }
  return parseFloat(strVal)
}
// 乘以100保留两位小数点
const multipliedByHundred = str => {
  let floatVal = parseFloat(str)
  if (isNaN(floatVal)) {
    return 0
  }
  floatVal = Math.round(str * 10000) / 100
  let strVal = floatVal.toString()
  let searchVal = strVal.indexOf('.')
  if (searchVal < 0) {
    searchVal = strVal.length
    strVal += '.'
  }
  while (strVal.length <= searchVal + 2) {
    strVal += '0'
  }
  return parseFloat(strVal)
}
// 规则校验并不小于0
const removeLeadingZerosAndEnsureNonNegative = inputStr => {
  // 使用正则表达式过滤掉除数字和小数点以外的字符
  const filteredStr = inputStr.replace(/[^0-9.]/g, '');

  // 使用正则表达式去掉前导零,但保留一个零作为整数部分
  let trimmedStr = filteredStr.replace(/^0+(?=\d)|^0+(?=\.)/, '');

  // 如果字符串以小数点结尾,不做任何修改
  if (trimmedStr === '.') {
    return '0.';
  }

  // 如果字符串以小数点开始,添加一个零作为整数部分
  if (trimmedStr.startsWith('.')) {
    trimmedStr = '0' + trimmedStr;
  }

  // // 如果小数点后没有数字,则在末尾添加一个零
  // if (trimmedStr.indexOf('.') !== -1 && trimmedStr.endsWith('.')) {
  //   trimmedStr += '0';
  // }
  // // 如果字符串以小数点结尾,不做任何修改
  // if (trimmedStr.endsWith('.')) {
  //   return trimmedStr;
  // }

  let [number, decimal] = trimmedStr.split('.')
  if (decimal != undefined) {
    decimal = decimal.substring(0, 2)
    number += `.${decimal}`
    trimmedStr = number
  }
  // 将字符串转换为浮点数
  const numberValue = parseFloat(trimmedStr);

  // 如果转换后的值为 NaN 或者小于 0,则默认为 0
  if (isNaN(numberValue) || numberValue < 0) {
    return 0;
  }
  // 如果转换后的值大于于 100000,则默认为 100000
  if (isNaN(numberValue) || numberValue > 100000) {
    return 100000;
  }
  return trimmedStr;
}


const format = {
  decimal,
  setPrice,
  dateFormatter,
  bigNumberTransform,
  tsFormatTime,
  numberFixedDigit,
  divideByHundred,
  multipliedByHundred,
  removeLeadingZerosAndEnsureNonNegative
}
export default format