Skip to content

DPI / PPI Calculator — TypeScript source

Compute screen pixel density (PPI/DPI), dot pitch, physical dimensions, and aspect ratio from any resolution. Solve for PPI from a diagonal, or derive the diagonal from a known PPI - all in your browser.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Display pixel-density math. Pure, deterministic, never throws.
//
// Non-positive inputs that cause division by zero produce NaN or Infinity
// (documented JS behavior) rather than throwing - callers should guard with
// Number.isFinite before display.

const MM_PER_INCH = 25.4;

/** Diagonal length in pixels: √(w² + h²). Sign of inputs is irrelevant (squared). */
export function diagonalPixels(w: number, h: number): number {
  return Math.sqrt(w * w + h * h);
}

/** Pixels per inch from resolution and a known diagonal (inches). */
export function computePpi({
  w,
  h,
  diagonalInches,
}: {
  w: number;
  h: number;
  diagonalInches: number;
}): { ppi: number } {
  return { ppi: diagonalPixels(w, h) / diagonalInches };
}

/** Physical dimensions from resolution + ppi. Returns inches and millimeters. */
export function physicalSize({
  w,
  h,
  ppi,
}: {
  w: number;
  h: number;
  ppi: number;
}): {
  widthIn: number;
  heightIn: number;
  diagonalIn: number;
  widthMm: number;
  heightMm: number;
} {
  const widthIn = w / ppi;
  const heightIn = h / ppi;
  return {
    widthIn,
    heightIn,
    diagonalIn: diagonalPixels(widthIn, heightIn),
    widthMm: widthIn * MM_PER_INCH,
    heightMm: heightIn * MM_PER_INCH,
  };
}

/** Dot pitch (pixel size) in millimeters per pixel = 25.4 / ppi. */
export function dotPitch(ppi: number): number {
  return MM_PER_INCH / ppi;
}

/** Integer gcd (Euclid), used to reduce aspect ratios. */
function gcd(a: number, b: number): number {
  let x = Math.abs(Math.trunc(a));
  let y = Math.abs(Math.trunc(b));
  while (y !== 0) {
    const t = y;
    y = x % y;
    x = t;
  }
  return x;
}

/** Reduced aspect ratio "w:h" (e.g. "16:9"). "-" if either side is non-positive. */
export function aspectRatio(w: number, h: number): string {
  if (!(w > 0) || !(h > 0)) return '-';
  const g = gcd(w, h);
  if (g === 0) return '-';
  return `${Math.trunc(w) / g}:${Math.trunc(h) / g}`;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →