JavaScript中比较好用且实用的代码集合【数字操作篇】

数字操作篇

1、判断是否为数字

//  利用位运算符实现判断
const isNumber = (value) => ((value | 0) === value);
isNumber('123x') // false
isNumber('0') // false
isNumber(123) // true
isNumber(0) // true
isNumber(null) // false
isNumber(undefined) // false

2、生成随机数

const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNum(1, 10) // 6
randomNum(10, 20) // 11

3、进制转换

// 假设数字10要转换成2进制
const toDecimal = (num, n = 10) => num.toString(n)
toDecimal(10, 2) // '1010'

// 10的2进制为1010
const toDecimalism = (num, n = 10) => parseInt(num, n)
toDecimalism(1010, 2)

4、四舍五入

const round = (n, decimals = 0) => Number(`${
      
      Math.round(`${ 
        n}e${ 
        decimals}`)}e-${
      
      decimals}`)
round(10.255, 2) // 10.26

5、数字补零

const replenishZero = (num, len, zero = 0) => num.toString().padStart(len, zero)
replenishZero(8, 2) // 08

6、数字截断

const toFixed = (n, fixed) => `${
      
      n}`.match(new RegExp(`^-?\d+(?:.\d{0,${
      
      fixed}})?`))[0]
toFixed(10.255, 2) // 10.25

猜你喜欢

转载自blog.csdn.net/xiaorunye/article/details/130642741