xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js 金融数字格式化 All In One

js 金融数字格式化 All In One

finance money number format

数字格式化

regex

`123456789`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
// "123,456,789"

\B
\d
{3}
()
?
!+
?=

https://regexper.com/#%2F\B(%3F%3D(\d{3})%2B(%3F!\d))%2Fg

Flags: Global
non-word boundary
positive lookahead
group #1
digit
2 times
negative lookahead

solutions


// 金融数字格式化
// 1234567890 --> 1,234,567,890

const log = console.log;

// 正则实现
const formatMoney = (str) => str.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

// 非正则实现
function formatCash(str) {
  return str.split('').reverse().reduce((prev, next, index) => {
    return ((index % 3) ? next : (next + ',')) + prev
  })
}

const test = '1234567890'

console.log(formatMoney('1234567890'));
// 1,234,567,890

console.log(formatCash('1234567890'));
// 1,234,567,890

// 非正则, js 实现
function formatCash(str) {
  return str.split('').reverse().reduce((prev, next, index) => {
    // reduce 不指定 init value, 默认取 arr[0] 做为 init value
    // reduce index 从 1 开始,不是 0 ⚠️
    console.log(`prev, next, index =`, prev, next, index);
    return ((index % 3 !== 0) ? next : (next + ',')) + prev
  })
}

formatCash('1234567890');

image

parseFloat / parseInt & toLocaleString

number tolocalString

const num = 123456789;
// 123456789

num.toString();
// "123456789"

num.toLocaleString();
// "123,456,789"

'1234567890'.toLocaleString();
// "1234567890"

parseFloat("1234567890").toLocaleString();
// "1,234,567,890"

parseInt("1234567890").toLocaleString();
// "1,234,567,890"

regex


const moneyFormat = num => {
  const str = num.toString();
  const len = str.length;
  if (len <= 3) {
    return str;
  } else {
    // 判断是否有小数, 截取小数部分
    const decimals = str.indexOf('.') > -1 ? str.split('.')[1] : ``;
    let foot = '';
    if(decimals) {
      foot = '.' + decimals;
    }
    let remainder = len % 3;
    if (remainder > 0) {
      // 不是 3 的整数倍, 有 head, 如(1234567.333 => 1, 234, 567.333)
      const head = str.slice(0, remainder) + ',';
      const body = str.slice(remainder, len).match(/\d{3}/g).join(',');
      return head + body + foot;
      // return str.slice(0, remainder) + ',' + str.slice(remainder, len).match(/\d{3}/g).join(',') + temp;
    } else {
      // 是 3 的整数倍, 无 head, 如(123456.333 => 123, 456.333)
      const body = str.slice(0, len).match(/\d{3}/g).join(',');
      return body + foot;
      // return str.slice(0, len).match(/\d{3}/g).join(',') + temp;
    }
  }
}


// `123456`.slice(0, 6).match(/\d{3}/);
// ["123", index: 0, input: "123456", groups: undefined]
// regex match return ???

// `123456`.slice(0, 6).match(/\d{3}/g);
// ["123", "456"]
// regex match g return all grounds

moneyFormat(123456.33);
// '123,456.33'

moneyFormat(123.33);
// '123.33'

regex $1,$2

function formatNum(num,n) {
    // num 要格式化的数字
    // n 保留小数位, 位数
    const regex = /(-?\d+)(\d{3})/;
    let str = num.toFixed(n).toString();
    while(regex.test(str)) {
      console.log(`\nstr 1 =`, str);
      str = str.replace(regex, "$1,$2");
      console.log(`str 2 =`, str);
    }
    return str;
}


formatNum(1234005651.789, 2);
// "1,234,005,651.79"

/*

str 1 = 1234005651.79
str 2 = 1234005,651.79

str 1 = 1234005,651.79
str 2 = 1234,005,651.79

str 1 = 1234,005,651.79
str 2 = 1,234,005,651.79

*/

千分位格式


// 金融数字格式化
// 1234567890 --> 1,234,567,890

js 模板引擎

js template engine


// templateEngine
const templateEngine = (str = ``, data = {}) => {
  const reg = /{{([^{}]+)?}}/g;
  let match, paths, key,template;

  while (match = reg.exec(str)) {
    console.log(`match`, match);
    templateHolder = match[0];
    // {{varibale}}
    key = match[1];
    // varibale
    paths = key.split('.');
    // ["k1", "k2"]
    console.log(`paths`, paths);
    let obj = data;
    // 遍历多级属性
    for (let i = 0; i < paths.length; i++) {
      obj = obj[paths[i]];
    }
    // 模板替换
    str = str.replace(template, obj);
  }
  return str;
}

const template = `<section><div>{{name}}</div><div>{{infos.city}}</div></section>`;

const data = {
  name: 'xgqfrms',
  infos:{
    city: 'ufo',
  }
}

templateEngine(template, data);
//"<section><div>xgqfrms</div><div>ufo</div></section>"

/*

match (2) ["{{name}}", "name", index: 14, input: "<section><div>{{name}}</div><div>{{infos.city}}</div></section>", groups: undefined]

paths ["name"]

match (2) ["{{infos.city}}", "infos.city", index: 33, input: "<section><div>{{name}}</div><div>{{infos.city}}</div></section>", groups: undefined]

paths (2) ["infos", "city"]

"<section><div>{{name}}</div><div>{{infos.city}}</div></section>"


*/


// const template = `<section><div>{{name}}</div><div>{{city}}</div></section>`;
// "<section><div>xgqfrms</div><div>undefined</div></section>"

refs

js number format All In One

JavaScript 格式化数字、金额、千分位、保留几位小数、舍入舍去, 百分比 %

https://www.cnblogs.com/xgqfrms/p/11759100.html

js 金融数字格式化 / js finance money number format

https://www.cnblogs.com/xgqfrms/p/12791249.html#4679119

regex

https://regexper.com/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-09-09 16:59  xgqfrms  阅读(720)  评论(7编辑  收藏  举报