numeral,格式化数字的使用

2,667 阅读1分钟

最近一直在忙项目,也没更新自己的笔记,今天遇见个问题,就是数据展示的问题,

后端返回的是 0.889012389.... 这么多位的小数,我想要的是 88.901% 精确3位,而且呢,我本来想着 这不简单么,直接 toFixed(3)解决,发现虽然能解决,但不精确,后来就搜到了额这个 numeral.js 

找了半天,包括官网都没介绍怎么用,最后发现一篇直接就说用法了,很好,这里我也copy一下,方便自己以后用的时候找不到

const numeral = require('numeral');

// 解析数字
numeral('10,000.12'); // 10000.12
numeral('$10,000.00'); // 10000
numeral('3.467TB'); // 3467000000000
numeral('-76%'); // -0.76

// 格式化
numeral(10000.23).format('0,0'); // '10,000'
numeral(10000.1234).format('0.000'); // '10000.123'
numeral(100.1234).format('00000'); // '00100'
numeral(1230974).format('0.0a'); // '1.2m'
numeral(100).format('0o'); // '100th'
numeral(1000.234).format('$0,0.00'); // '$1,000.23'
numeral(7884486213).format('0.00b'); // '7.88GB'
numeral(0.974878234).format('0.000%'); // '97.488%'
numeral(238).format('00:00:00'); // '17:44:06'

numeral 支持普通数字、小数、货币、字节、百分比、时间等数字格式。