随机数范围

  1. export const random = (min, max) => {
  2. if (arguments.length === 2) {
  3. return Math.floor(min + Math.random() * ((max + 1) - min))
  4. } else {
  5. return null;
  6. }
  7. }
  8. function randomNum(minNum: number, maxNum: number) {
  9. return parseInt(`${Math.random() * (maxNum - minNum + 1) + minNum}`, 10)
  10. }
  1. export const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

小数转百分数 保留两位小数

  1. Number(0.8965456465156 * 100).toFixed(2) + "%"

保留小数点以后 n 位

  1. // 保留小数点以后几位,默认2位
  2. export function cutNumber(number, no = 2) {
  3. if (typeof number != 'number') {
  4. number = Number(number)
  5. }
  6. return Number(number.toFixed(no))
  7. }

bytes 字节单位自动转化 MB GB …等

  1. function bytesToSize(bytes: number | string) {
  2. if (isString(bytes)) {
  3. bytes = Number(bytes)
  4. }
  5. if (bytes === 0) {
  6. return { size: 0, switchSize: 0, unit: 'MB' }
  7. }
  8. let sign = '+'
  9. if (bytes < 0) {
  10. bytes = Math.abs(bytes)
  11. sign = '-'
  12. }
  13. const k = 1024
  14. const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  15. const unitIndex = Math.floor(Math.log(bytes) / Math.log(k))
  16. let switchSize = bytes / Math.pow(k, unitIndex)
  17. if (sign === '-') {
  18. bytes = -bytes
  19. switchSize = -switchSize.toFixed(2)
  20. }
  21. return {
  22. size: bytes,
  23. switchSize: switchSize,
  24. unit: units[unitIndex >= units.length ? units.length - 1 : unitIndex]
  25. }
  26. }

判断奇数偶数

  1. const isEven = num => num % 2 === 0;
  2. console.log(isEven(2));
  3. // Result: true
  4. console.log(isEven(3));
  5. // Result: false

格式化金钱

项目中我们经常会遇到金钱格式化需求,或者说数字格式化一下,方便阅读(数字比较大的情况下)
比如说 999999999,直接阅读很不直观,格式化后 999,999,999

  1. //正则
  2. function formatPrice(price) {
  3. return String(price).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  4. }
  5. function formatPrice(price) {
  6. return String(price)
  7. .split('')
  8. .reverse()
  9. .reduce((prev, next, index) => {
  10. return (index % 3 ? next : next + ',') + prev;
  11. });
  12. }
  13. (999999999).toLocaleString(); // 999,999,999
  14. // 当然还可以更秀一点
  15. const options = {
  16. style: 'currency',
  17. currency: 'CNY',
  18. };
  19. (123456).toLocaleString('zh-CN', options); // ¥123,456.00

toLocaleString 可以接收两个可选参数:locales 和 options,而且这个 api 在各大浏览器通用不存在兼容问题并且这个 api 不止存在 Number 的原型上,Array、Object、Date 原型上都有这个 api,并且格式化出来的值可以根据我们传入的参数出现各种结果,参数及用法可以参考 MDN

数字转化为大写金额

  1. const digitUppercase = (n) => {
  2. const fraction = ["角", "分"];
  3. const digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  4. const unit = [
  5. ["元", "万", "亿"],
  6. ["", "拾", "佰", "仟"],
  7. ];
  8. n = Math.abs(n);
  9. let s = "";
  10. for (let i = 0; i < fraction.length; i++) {
  11. s += (
  12. digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]
  13. ).replace(/零./, "");
  14. }
  15. s = s || "整";
  16. n = Math.floor(n);
  17. for (let i = 0; i < unit[0].length && n > 0; i++) {
  18. let p = "";
  19. for (let j = 0; j < unit[1].length && n > 0; j++) {
  20. p = digit[n % 10] + unit[1][j] + p;
  21. n = Math.floor(n / 10);
  22. }
  23. s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
  24. }
  25. return s
  26. .replace(/(零.)*零元/, "元")
  27. .replace(/(零.)+/g, "零")
  28. .replace(/^整$/, "零元整");
  29. };

数字转中文数字

  1. export const intToChinese = (value) => {
  2. const str = String(value);
  3. const len = str.length-1;
  4. const idxs = ['','十','百','千','万','十','百','千','亿','十','百','千','万','十','百','千','亿'];
  5. const num = ['零','一','二','三','四','五','六','七','八','九'];
  6. return str.replace(/([1-9]|0+)/g, ( $, $1, idx, full) => {
  7. let pos = 0;
  8. if($1[0] !== '0'){
  9. pos = len-idx;
  10. if(idx == 0 && $1[0] == 1 && idxs[len-idx] == '十'){
  11. return idxs[len-idx];
  12. }
  13. return num[$1[0]] + idxs[len-idx];
  14. } else {
  15. let left = len - idx;
  16. let right = len - idx + $1.length;
  17. if(Math.floor(right / 4) - Math.floor(left / 4) > 0){
  18. pos = left - left % 4;
  19. }
  20. if( pos ){
  21. return idxs[pos] + num[$1[0]];
  22. } else if( idx + $1.length >= len ){
  23. return '';
  24. }else {
  25. return num[$1[0]]
  26. }
  27. }
  28. });
  29. }