js 金融数字格式化

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

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

Array all in one

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



xgqfrms 2012-2020

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


js 金融数字格式化的更多相关文章

  1. js金额数字格式化实现代码(三位加逗号处理保留两位置小数)

    工作中很常用的东西: 例1,使数字1111111变成11,111,111.00,保留两位小数. <html> <head> <script type="text ...

  2. js 实现数字格式化(货币格式)几种方法

    // 方法一 function toThousands(num) { var result = [ ], counter = 0; num = (num || 0).toString().split( ...

  3. JS实现数字千位符格式化方法

    /** * [number_format 参数说明:] * @param {[type]} number [number:要格式化的数字] * @param {[type]} decimals [de ...

  4. 数字格式化的 js 库

    数字格式化的 js 库 Numeral.js,是一个用于格式化数字和处理数字的 js 库. Tip:目前 Star 有 9.2k,5年以前就没有在更新.其文档写得不很清晰,比如它提供了多语言,但如何切 ...

  5. js数字格式化-四舍五入精简版

    搜索网上的,数字格式化过余复杂,自己想了个简单方法,欢迎吐槽. 简化说明: '123333' => 12.3万 parseInt('123333') 字符串转整型 parseInt('12333 ...

  6. js数字格式化(截断格式化或四舍五入格式化)

    /*** * 数字格式化(适合金融产品截断小数位后展示) * @param num * @param pattern (标准格式:#,###.## 或#.## 或#,###00.00) * @para ...

  7. JS前端数据格式化

    当我们从后台取了数据,但是我们希望在前台统一显示格式时,我们可能需要格式化数据. 今天正好总结一下前端JS格式化数据的几个方法: 1. toFixed() 方法   可把 Number 四舍五入为指定 ...

  8. 使用 .toLocaleString() 轻松实现多国语言价格数字格式化

    用代码对数字进行格式化,显然不是逢三位加逗号这么简单.比如印度在数字分位符号上的处理,就堪称业界奇葩: 印度的数字读法用“拉克”(十万)和“克若尔”(千万),数字标法用不对称的数位分离,即小数点左侧首 ...

  9. JavaScript 系列--JavaScript一些奇淫技巧的实现方法(二)数字格式化 1234567890转1,234,567,890;argruments 对象(类数组)转换成数组

    一.前言 之前写了一篇文章:JavaScript 系列--JavaScript一些奇淫技巧的实现方法(一)简短的sleep函数,获取时间戳 https://www.mwcxs.top/page/746 ...

随机推荐

  1. C++ Primer Plus读书笔记(二)处理数据

    1.格式化输出: 和C语言不太一样,C++格式化输出进制格式如下: 1 int a = 42; 2 int b = 42; 3 int c = 42; 4 5 cout << a < ...

  2. 【Redis 分布式锁】(1)一把简单的“锁”

    原文链接:https://www.changxuan.top/?p=1230 在单体架构向分布式集群架构演进的过程中,项目中必不可少的一个功能组件就是分布式锁.在开发团队有技术积累的情况下,做为团队的 ...

  3. IO多路复用与epoll机制浅析

    epoll是Linux中用于IO多路复用的机制,在nginx和redis等软件中都有应用,redis的性能好的原因之一也就是使用了epoll进行IO多路复用,同时epoll也是各大公司面试的热点问题. ...

  4. Excel 常用数据类型、自定义格式、特殊值等等

    常用数据类型: 常规: 常规单元榴格式不包含慑拍H靛的数字格式. 数值: 可以设置小数位数,是否使用千位分割符,以及负数样式 货币: 可以设置小数位数,货币符号,以及负数样式 会计专用: 可以设置小数 ...

  5. XCTF-easyjni

    前期工作 查壳无壳 逆向分析 文件结构 MainActivity代码 public class MainActivity extends c { static { System.loadLibrary ...

  6. Mysql 5.5升级5.8

    前言,因为升级跳板机,需要将mariadb 升级到10.2,也就是对应MySQL的5.8,废话不多说下面开始进行mariadb 5.5 的升级 Welcome to the MariaDB monit ...

  7. Openstack (keystone 身份认证)

    keystone简介 keystone 是OpenStack的组件之一,用于为OpenStack家族中的其它组件成员提供统一的认证服务,包括身份验证.令牌的发放和校验.服务列表.用户权限的定义等等.云 ...

  8. Manthan, Codefest 19 (open for everyone, rated, Div. 1 + Div. 2) E. Let Them Slide(数据结构+差分)

     题意:问你有n个长度总和为n的数组 你可以移动数组 但不能移出长度为w的矩形框 问你每一列的最大值是多少? 思路:只有一次询问 我们可以考虑差分来解决 然后对于每一行数组 我们可以用数据结构维护一下 ...

  9. 【poj 2478】Farey Sequence(数论--欧拉函数 找规律求前缀和)

    题意:定义 Fn 序列表示一串 <1 的分数,分数为最简分数,且分母 ≤n .问该序列的个数.(2≤N≤10^6) 解法:先暴力找规律(代码见屏蔽处),发现 Fn 序列的个数就是 Φ(1)~Φ( ...

  10. 带有Python的音频处理(附带源码)

    由于博客播放不了音频,所以音频将以视频形式展现.公众号也正在进行抽书 音频素材请点击这里进行观看 往下拉就是文章地址 有时,在进行编程时,我们需要进行一些音频处理.编程中最常用的音频处理任务包括–加载 ...