Dromo WebinarLearn how Dromo can solve your data importing problems

Register now

Formatting Numbers

Modifying how a number is displayed without altering the underlying data.

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

ProductPrice
Shirt30
Shoes"80"
Cap15

After

ProductPriceFormattedError
Shirt30$30.00
Shoes"80""80"Error: price field is not a number
Cap15$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.
  • 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.