返回一个由给定数字的商和余数组成的数组
// 返回一个由给定数字的商和余数组成的数组。const divmod = (x: number, y: number) => [Math.floor(x / y), x % y];divmod(8, 3); // [2, 2]divmod(3, 8); // [0, 3]divmod(5, 5); // [1, 0]
检查给定的数字是否在给定范围内
使用算术比较来检查给定的数字是否在指定范围内。
如果未指定 end 参数 ,则认为范围为 0 到 start 。
const inRange = (n, start, end = null) => {if (end && start > end) [end, start] = [start, end];return end == null ? n >= 0 && n < start : n >= start && n < end;};inRange(3, 2, 5); // trueinRange(3, 4); // trueinRange(2, 3, 5); // falseinRange(3, 2); // false
clamp 返回限制在 lower 和 upper 之间的值
/*** @Description: 返回限制在 lower 和 upper 之间的值* @param {*} value* @param {*} min* @param {*} max*/export function clamp(value: number, min: number, max: number): number {if (value < min) {return min} else if (value > max) {return max}return value}
随机数范围
export const random = (min, max) => {if (arguments.length === 2) {return Math.floor(min + Math.random() * ((max + 1) - min))} else {return null;}}function randomNum(minNum: number, maxNum: number) {return parseInt(`${Math.random() * (maxNum - minNum + 1) + minNum}`, 10)}
export const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
小数转百分数 保留两位小数
Number(0.8965456465156 * 100).toFixed(2) + "%"
保留小数点以后 n 位
// 保留小数点以后几位,默认2位export function cutNumber(number, no = 2) {if (typeof number != 'number') {number = Number(number)}return Number(number.toFixed(no))}
bytes 字节单位自动转化 MB GB …等
未考虑负数
export function switchUnit(n: number) {const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']let unitIndex = Math.floor(Math.log(n) / Math.log(1024))unitIndex = Math.min(unitIndex,units.length - 1)const size = n / 1024 ** unitIndexreturn {size: size.toFixed(2),unit: units[unitIndex >= units.length ? units.length - 1 : unitIndex]}}
兼容负数
function bytesToSize(bytes: number | string) {if (isString(bytes)) {bytes = Number(bytes)}if (bytes === 0) {return { size: 0, switchSize: 0, unit: 'MB' }}let sign = '+'if (bytes < 0) {bytes = Math.abs(bytes)sign = '-'}const k = 1024const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']let unitIndex = Math.floor(Math.log(bytes) / Math.log(k))unitIndex = Math.min(unitIndex,units.length - 1)let switchSize = bytes / Math.pow(k, unitIndex)if (sign === '-') {bytes = -bytesswitchSize = -switchSize.toFixed(2)}return {size: bytes,switchSize: switchSize,unit: units[unitIndex >= units.length ? units.length - 1 : unitIndex]}}
1000进位
const prettyBytes = (num, precision = 3, addSpace = true) => {const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3),UNITS.length - 1);const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];};prettyBytes(1000); // '1 KB'prettyBytes(-27145424323.5821, 5); // '-27.145 GB'prettyBytes(123456789, 3, false); // '123MB'
判断奇数偶数
const isEven = num => num % 2 === 0;console.log(isEven(2));// Result: trueconsole.log(isEven(3));// Result: false
格式化金钱
项目中我们经常会遇到金钱格式化需求,或者说数字格式化一下,方便阅读(数字比较大的情况下)
比如说 999999999,直接阅读很不直观,格式化后 999,999,999
//正则function formatPrice(price) {return String(price).replace(/\B(?=(\d{3})+(?!\d))/g, ',');}function formatPrice(price) {return String(price).split('').reverse().reduce((prev, next, index) => {return (index % 3 ? next : next + ',') + prev;});}(999999999).toLocaleString(); // 999,999,999// 当然还可以更秀一点const options = {style: 'currency',currency: 'CNY',};(123456).toLocaleString('zh-CN', options); // ¥123,456.00
toLocaleString 可以接收两个可选参数:locales 和 options,而且这个 api 在各大浏览器通用不存在兼容问题并且这个 api 不止存在 Number 的原型上,Array、Object、Date 原型上都有这个 api,并且格式化出来的值可以根据我们传入的参数出现各种结果,参数及用法可以参考 MDN
数字转化为大写金额
const digitUppercase = (n) => {const fraction = ["角", "分"];const digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];const unit = [["元", "万", "亿"],["", "拾", "佰", "仟"],];n = Math.abs(n);let s = "";for (let i = 0; i < fraction.length; i++) {s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, "");}s = s || "整";n = Math.floor(n);for (let i = 0; i < unit[0].length && n > 0; i++) {let p = "";for (let j = 0; j < unit[1].length && n > 0; j++) {p = digit[n % 10] + unit[1][j] + p;n = Math.floor(n / 10);}s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;}return s.replace(/(零.)*零元/, "元").replace(/(零.)+/g, "零").replace(/^整$/, "零元整");};
数字转中文数字
export const intToChinese = (value) => {const str = String(value);const len = str.length-1;const idxs = ['','十','百','千','万','十','百','千','亿','十','百','千','万','十','百','千','亿'];const num = ['零','一','二','三','四','五','六','七','八','九'];return str.replace(/([1-9]|0+)/g, ( $, $1, idx, full) => {let pos = 0;if($1[0] !== '0'){pos = len-idx;if(idx == 0 && $1[0] == 1 && idxs[len-idx] == '十'){return idxs[len-idx];}return num[$1[0]] + idxs[len-idx];} else {let left = len - idx;let right = len - idx + $1.length;if(Math.floor(right / 4) - Math.floor(left / 4) > 0){pos = left - left % 4;}if( pos ){return idxs[pos] + num[$1[0]];} else if( idx + $1.length >= len ){return '';}else {return num[$1[0]]}}});}
进制转化
十进制 <> 十六进制
const decimalToHex = dec => dec.toString(16);decimalToHex(0); // '0'decimalToHex(255); // 'ff'
const hexToDecimal = hex => parseInt(hex, 16);hexToDecimal('0'); // 0hexToDecimal('ff'); // 255
