当前位置:网站首页>js 实现千分位
js 实现千分位
2022-08-06 00:38:00 【hzxOnlineOk】
如何对一大串数值进行千分位、万分位等方式分隔,使用户阅读更加便利,以下介绍3种方法
方法一:使用正则
function regexHandleNum(num) {
return String(num).replace(/\B(?=(\d{3})+(?!\d))/g, ','); // 3是千分位,4是万分位
}
方法二:使用js自带的数组方法进行处理千分位
function handleNum(num) {
return String(num)
.split('')
.reverse()
.reduce((prev, next, index) => {
return (index % 3 ? next : next + ',') + prev; // 3是千分位,4是万分位
});
}
方法三:使用JS内置 API (toLocaleString),实现数字、金额等等数值的格式化
(111111111).toLocaleString(); // 111,111,111 这种是没有单位的
// 还可以通过2个参数,进行不同数据的处理,例如人民币格式、百分比格式
const opts = {
style: 'currency',
currency: 'CNY',
};
(111111111).toLocaleString('zh-CN', opts); // ¥111,111,111.00
const opts = {
style: 'percent',
currency: 'CNY',
};
(0.5).toLocaleString('zh-CN', opts); // 50%
更多用法请参考MDN
toLocaleString 可以接收两个可选参数:locales 和 options,而且这个 api在各大浏览器通用不存在兼容问题并且这个 api 不止存在 Number 的原型上,Array、Object、Date 原型上都有这个 api,并且格式化出来的值可以根据我们传入的参数出现各种结果。
关于toLocaleString的参数及用法在MDN(Number.prototype.toLocaleString())中有详细的用法。
边栏推荐
猜你喜欢

Kubernetes网络模型

Use WeChat to scan the code to log in

How to align the WeChat applet capsule button?

Viola-Jones Detector (VJ)---Study Notes

【论文阅读】Virtual Adversarial Training: a Regularization Method for SL and SSL

Security Testing - Data Security Testing (2)

ERP库存管理

NFT 游戏含义:游戏中的 NFT 是什么?

为啥强烈禁止使用Calendar?

【电商运营】网上商店如何利用好自己的营销数据达成目标?
随机推荐
NFT 游戏含义:游戏中的 NFT 是什么?
redis面试题
openstack架构中给虚拟机提供存储资源的组件是什么
子页面监听父页面点击事件
【mysql】--记一次delete删除语句使用别名的坑
架构基本概念和架构本质
Go 语言 strings 库常用方法
Convert the children array to a one-bit array
Kubernetes网络模型
el-table的暂无数据怎么变成图片加文字按钮?
代码随想录笔记_动态规划_494目标和
iNFTnews | 元宇宙将如何改变教育?
ERP库存管理
华为分析&联运活动,助您提升游戏总体付费
shell之函数和数组
白话机器学习-卷积神经网络CNN
[kali-vulnerability exploitation] (3.2) Metasploit basics (middle): Armitage tool exploitation process
为啥强烈禁止使用Calendar?
datatables encapsulates the parameters passed to the background and the parameters that are split and passed back
Using a shell script: Shut down a specific process