Skip to content

Instantly share code, notes, and snippets.

@wulucxy
Last active July 9, 2018 02:31
Show Gist options
  • Save wulucxy/5f89aa88830fcaee2ca4a87484ed89eb to your computer and use it in GitHub Desktop.
Save wulucxy/5f89aa88830fcaee2ca4a87484ed89eb to your computer and use it in GitHub Desktop.
Number #snippet

Number

formatNumberByThousand

将数字修改为千分位计数方式

const formatNumberByThousand = (value) => {
  return value && value.toLocaleString('en-us')
}

Demo:

formatNumberByThousand(100000) // '100,000'

numberFormatter

当数字过大时,需要将数字转化为k,M,B等格式。 接收两个参数,第一个为需要转化的数字,第二个是保留的小数点位数,默认为1

const numberFormatter = (num, digits = 1) => {
  const formatter = [
    { value: 1, symbol: '' },
    { value: 1E3, symbol: 'k' },
    { value: 1E6, symbol: 'M' },
    { value: 1E8, symbol: 'B' }
  ]

  const numberRegex = /\.0+$|(\.[0-9]*[1-9])0+$/

  var i
  // 倒序开始
  for (i = formatter.length - 1; i > 0; i--) {
    // 如果传入值大于 formatter 指定的值,直接跳出循环,设置为当前索引值
    if (num >= formatter[i].value) {
      break
    }
  }

  return (num / formatter[i].value).toFixed(digits).replace(numberRegex, '$1') + formatter[i].symbol
}

Demo:

numberFormatter(2979245) => 3M
numberFormatter(1234.456, 2) => 1.23k
numberFormatter(12343232323.456, 2) => 123.43B
numberFormatter(123.456, 2) => 123.46

inRange

给予一个最小值和最大值,如果传入的值介于最小值和最大值之间,则直接返回传入值,如果小于最小值,则取最小值;如果大于最大值,则取最大值。

const inRange = (value, {minValue = 0, maxValue}) => {
  return Math.max(minValue, Math.min(maxValue, value))
}

Demo:

inRange(10, {minValue: 1, maxValue:10})  // 10
inRange(10, {minValue: 20, maxValue:100}) // 20
inRange(10, {maxValue: 5}) // 5

randomIntegerInRange

生成区间之内随机整数。

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min

Demo:

andomIntegerInRange(0, 100) // 52: 生成一个随机整数值

randomId

生成随机带字符、数字的 id, 默认11位。参数 count 可以配置生成的随机值位数。

const randomId = (count = 0) => Math.random().toString(36).substr(2).slice(-count)

Demo:

randomId() // 'dt30s43a34m'
randomId(5) // 'xj6w5'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment