DNI Formula - Mathematical Calculation and Verification

The DNI formula is the official mathematical method used to calculate the verification letter of the Spanish National Identity Document. This system, implemented in 1962, allows detecting transcription errors and ensuring the validity of the document.

Related tools:

Mathematical formula

Letter = TABLE[ dni_number MOD 23 ]

Where:

  • dni_number: The 8 digits of the DNI
  • MOD: Modulo operation (remainder of division)
  • 23: Prime number chosen for the algorithm
  • TABLE: Array of ordered valid letters

Step by step example

For the DNI: 12345678

  1. Division: 12345678 ÷ 23 = 536768.608...
  2. Decimal part: 0.608... × 23 = 14
  3. Remainder (modulo): 14
  4. Corresponding letter: TABLE[14] = Z
  5. Final result: 12345678Z

Implementation in different languages

PHP


function calcularLetraDNI($numero) {
    $letras = "TRWAGMYFPDXBNJZSQVHLCKE";
    return $letras[$numero % 23];
}
                    

JavaScript


function calcularLetraDNI(numero) {
    const letras = "TRWAGMYFPDXBNJZSQVHLCKE";
    return letras[numero % 23];
}
                    

Python


def calcular_letra_dni(numero):
    letras = "TRWAGMYFPDXBNJZSQVHLCKE"
    return letras[numero % 23]
                    

Why is the number 23 used?

  • It is a prime number
  • It matches the number of available valid letters
  • It provides a uniform distribution
  • It minimizes transcription errors

Propiedades matemáticas

  • Inyectividad: Cada número genera una única letra
  • Distribución uniforme: Todas las letras tienen similar probabilidad
  • Detección de errores: Cambios en el número producen diferentes letras
  • Detección de transposiciones: El intercambio de dígitos suele cambiar la letra

Frequently asked questions

¿Qué errores puede detectar la fórmula?

La fórmula puede detectar errores de transcripción de un solo dígito y la mayoría de las transposiciones (intercambio de dígitos adyacentes).

Has the formula changed over time?

No, the formula has remained the same since its implementation in 1962 to maintain compatibility.

¿Otros documentos usan la misma fórmula?

Sí, el NIE (Número de Identidad de Extranjero) utiliza la misma fórmula, sustituyendo la letra inicial por un número (X=0, Y=1, Z=2) antes del cálculo.