formatCents

formatCents converts a cent integer to a formatted number string using Intl.NumberFormat.

Currency symbol rendering is left to the caller, keeping this function framework-agnostic and independently testable.

When to use

  • Displaying prices from backend cent values without coupling to a Redux store or React context.
  • Formatting order totals, line item prices, or shipping costs in UI components.

Behavior notes

  • Input is divided by 100 to produce a dollar value.
  • Thousand separators are added for values ≥ 1,000.
  • Negative values preserve the minus sign.
  • Defaults to 2 decimal places; pass a second argument to override.

Examples

formatCents(1250);
// "12.50"
formatCents(100000);
// "1,000.00"
formatCents(-500);
// "-5.00"
formatCents(1250, 0);
// "13"

Usage

import { formatCents } from '@branditdev/utils';

const lineItemPrice = 1250;
const orderTotal = 100000;
const discountedPrice = -500;

export const formatCentsDemo = {
  lineItem: formatCents(lineItemPrice),
  orderTotal: formatCents(orderTotal),
  discount: formatCents(discountedPrice),
  wholeNumber: formatCents(lineItemPrice, 0),
};

API

formatCents(cents, decimals?): string

Defined in: number/formatCents/formatCents.ts:23

Formats an integer cent value as a locale-formatted number string.

Returns a plain number string (e.g. "12.50"). Currency symbol rendering is intentionally left to the caller so this function remains framework-agnostic and testable in isolation.

Parameters

NameTypeOptionalDefaultDescription
centsnumberno-Integer cent value (e.g. 1250 → "12.50")
decimalsnumberyes2Decimal places, defaults to 2

Returns

string

A formatted number string with thousand separators.

Source

export function formatCents(cents: number, decimals = 2): string {
  return new Intl.NumberFormat('en-US', {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  }).format(cents / 100);
}