我們?nèi)粘i_發(fā)中,時常會碰到數(shù)值格式化操作的場景,今天了不起就為大家分享一款相對比較全面的數(shù)值格式化的JS庫:Numeral.js
Numeral.js
Numeral.js 是一個用來對數(shù)值進行操作和格式化的 JS 庫??蓪?shù)字格式化為貨幣、百分比、時間,甚至是序數(shù)詞的縮寫(比如1st,100th)。
安裝
下載到本地引入
<script src="numeral.min.js"></script>
或使用CDN路徑
<script src="http://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
當然,Node.js 環(huán)境還可以使用npm包。
npm install numeral
使用
在需要用到的地方聲明即可
var numeral = require('numeral');
這相當于創(chuàng)建一個numeral實例
。接著就可以拿著這個實例使用了。
- 數(shù)字格式化
numeral(1000).format('0,0');
// '1,000'
numeral(1234).format('0,0');
// 1,234 不帶小數(shù)
numeral(1234).format('0,0.00');
// 1,234.00 保留兩位小數(shù)
numeral(1).format('0o');
// 1st
numeral(2).format('0o');
// 2nd
numeral(10).format('0o');
// 10th
表中的格式完全夠日常開發(fā)所用了。
- 貨幣格式化
numeral(1000.234).format('$0,0.00');
// $1,000.23
ps:自動千分位分隔,四舍五入取值。
- 字節(jié)格式化
ps:字節(jié)格式化主要用在存儲統(tǒng)計上。
- 百分比格式化
遵循四舍五入規(guī)則,小數(shù)轉(zhuǎn)換為百分比,同時避免了浮點運算精度的問題。
numeral(0.144252).format('0.00%');
// 14.43% 小數(shù)點四舍五入
ps:如果直接將0.144252乘以100,會得到什么結(jié)果呢?大家不妨試試!
- 時間格式化
numeral(238).format('00:00:00');
// 0:03:58
- 指數(shù)格式化
numeral(1123456789).format('0.0e+0');// 1.1e+9
numeral(0.000134255).format('0.0e+0');// 1.3e-4
這也就是我們的科學計數(shù)法表示方式。
- 計算相關(guān)
哈哈,加、減、乘、除來一套!
var number = numeral(1000);
var result = number.add(100);
// 1100
其他
除了上面的方法之外,numeral.js 中還包括設(shè)值、差異求值、復制克隆、本地化、自定義格式等方法和功能。歡迎大家查閱下發(fā)地址進一步了解。文章來源:http://www.zghlxwxcb.cn/news/detail-437973.html
Github地址:https://github.com/adamwdraper/Numeral-js
官方網(wǎng)站:
http://numeraljs.com文章來源地址http://www.zghlxwxcb.cn/news/detail-437973.html
到了這里,關(guān)于大幅提升前端工作效率!Numeral.js數(shù)值格式化庫來了!的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!