Definition
Formatting numbers involves validating that a field's value is a number and then modifying its display without altering the underlying data. This process includes adding commas as thousands separators, fixing the number of decimal places, or converting the number into a percentage or currency format.
Formatting numbers is an important step to improve the readability of numerical data.
Example of formatting numbers using JavaScript
This example checks if the price
field is a number and then formats it into a currency string:
function formatNumber(data, field) {
return data.map((item) => {
if (typeof item[field] === "number") {
item.formatted = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(item[field]);
} else {
item.error = `Error: ${field} field is not a number`;
}
return item;
});
}
const data = [
{ product: "Shirt", price: 30 },
{ product: "Shoes", price: "80" },
{ product: "Cap", price: 15 },
];
const formattedData = formatNumber(data, "price");
Before
Product | Price |
---|---|
Shirt | 30 |
Shoes | "80" |
Cap | 15 |
After
Product | Price | Formatted | Error |
---|---|---|---|
Shirt | 30 | $30.00 | |
Shoes | "80" | "80" | Error: price field is not a number |
Cap | 15 | $15.00 |
Considerations
- Type Checking: Always validate that the value is indeed a number before attempting to format it. Failure to do so might lead to unexpected results or errors.
- Locale: When formatting numbers, especially into currency, consider the locale. Different regions use different currency symbols, decimal separators, and digit grouping methods.
- Underlying Data: Remember, number formatting changes only the display of data, not the actual data itself. Be aware of this when performing subsequent operations that require numerical inputs.
Related Operations
- Trimming Fields: It might be necessary to trim fields before validating and formatting numbers, especially if the data entry includes unwanted spaces.
- Standardizing Date Formats. This is a similar operation used for date types instead of numbers.