# Numeral.js
一个用于格式化和处理数字的javascript库
## 安装
~~~
npm install numeral
var numeral = require('numeral');
~~~
#### 创建一个数字实例。数字接受尝试转换为数字的数字或字符串。
~~~
var myNumeral =数字(1000);
var value = myNumeral.value();
// 1000
var myNumeral2 =数字('1,000');
var value2 = myNumeral2.value();
// 1000
~~~
#### 可以将数字设置为看起来像货币,百分比,时间,甚至是带有小数位,千位和缩写的普通旧数字。而且,您始终可以[创建自定义格式](http://numeraljs.com/#custom-formats)。
~~~
var string = numeric(1000).format('0,0');
//'1,000'
~~~
## 示例
~~~
var number = numeral(1000);
var string = number.format('0,0');
// '1,000'
var value = number.value();
// 1000
var number = numeral(1000);
var added = number.add(10);
// 1010
var number = numeral();
number.set(1000);
var value = number.value();
// 1000
var number = numeral(1000),
value = 100;
var difference = number.difference(value);
// 900
var a = numeral(1000);
var b = numeral(a);
var c = a.clone();
var aVal = a.set(2000).value();
// 2000
var bVal = b.value();
// 1000
var cVal = c.add(10).value();
// 1010
var number = numeral(1000);
number.format();
// '1,000'
numeral.defaultFormat('$0,0.00');
number.format();
// '$1,000.00'
var number = numeral(0);
var nullNumber = numeral(null);
numeral.zeroFormat('N/A');
numeral.nullFormat('N/A');
var zero = number.format('0.0')
// 'N/A'
var na = nullNumber.format('0.0')
// 'N/A'
// load a locale
numeral.register('locale', 'fr', {
delimiters: {
thousands: ' ',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal : function (number) {
return number === 1 ? 'er' : 'ème';
},
currency: {
symbol: '€'
}
});
// switch between locales
numeral.locale('fr');
// load a format
numeral.register('format', 'percentage', {
regexps: {
format: /(%)/,
unformat: /(%)/
},
format: function(value, format, roundingFunction) {
var space = numeral._.includes(format, ' %') ? ' ' : '',
output;
value = value * 100;
// check for space before %
format = format.replace(/\s?\%/, '');
output = numeral._.numberToFormat(value, format, roundingFunction);
if (numeral._.includes(output, ')')) {
output = output.split('');
output.splice(-1, 0, space + '%');
output = output.join('');
} else {
output = output + space + '%';
}
return output;
},
unformat: function(string) {
return numeral._.stringToNumber(string) * 0.01;
}
});
// use your custom format
numeral().format('0%');
~~~