随机数范围
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 …等
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 = 1024
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const unitIndex = Math.floor(Math.log(bytes) / Math.log(k))
let switchSize = bytes / Math.pow(k, unitIndex)
if (sign === '-') {
bytes = -bytes
switchSize = -switchSize.toFixed(2)
}
return {
size: bytes,
switchSize: switchSize,
unit: units[unitIndex >= units.length ? units.length - 1 : unitIndex]
}
}
判断奇数偶数
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: true
console.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]]
}
}
});
}