Quick Start Guide
This guide will walk you through the basic steps to start using Numeral.js for formatting and manipulating numbers.
1. Include Numeral.js
First, make sure you have Numeral.js included in your project. If you're in a browser environment, you can use a CDN:
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
In a Node.js environment, you would use require:
const numeral = require('numeral');
2. Create a Numeral Object
The core of the library is the numeral() function, which wraps a number and returns a Numeral object. You can pass a number, a string, or null to it.
var number = numeral(1234.56);
var stringNumber = numeral('2,345.67');
3. Format the Number
Use the .format() method on the Numeral object to convert it into a formatted string. You provide a format string to define how the number should be displayed.
// Format with thousand separators and two decimal places
var formatted = numeral(1234.56).format('0,0.00');
console.log(formatted); // Output: "1,234.56"
// Format as currency
var currency = numeral(1234.56).format('$0,0.00');
console.log(currency); // Output: "$1,234.56"
4. Manipulate the Number
Numeral.js provides methods for common mathematical operations. These methods modify the underlying value of the Numeral object.
var number = numeral(100);
number.add(50); // number is now 150
number.subtract(25); // number is now 125
number.multiply(2); // number is now 250
number.divide(5); // number is now 50
5. Get the Value
To retrieve the raw numeric value from a Numeral object, use the .value() method.
var number = numeral(123.45);
console.log(number.value()); // Output: 123.45
6. Chain Methods
One of the powerful features of Numeral.js is method chaining. You can combine manipulation and formatting calls in a single, readable line.
var result = numeral(500.25)
.add(100)
.multiply(2)
.format('$0,0.00');
console.log(result); // Output: "$1,200.50"
That's it! You've learned the basics of Numeral.js. Explore the Usage Guide for more advanced formatting options and features.