strToNumber
Paquete: @tiendana/utils
Convierte un string a número de forma segura, lanzando un error si la conversión no es posible. Acepta tanto strings como números como input.
Características
✅ Conversión segura string → number
✅ Acepta números como input (retorna sin modificar)
✅ Lanza error descriptivo si no puede convertir
✅ Soporta enteros y decimales
✅ Type-safe con TypeScript
✅ Validación estricta
Firma
function strToNumber(value: number | string): number
Parámetros
| Parámetro | Tipo | Descripción | Requerido |
|---|---|---|---|
value | number | string | Valor a convertir a número | ✅ |
Retorno
Tipo: number
El valor como número si la conversión es exitosa.
Lanza Error: Si value no puede ser convertido a número.
Ejemplos de Uso
Conversión Básica
import { strToNumber } from '@tiendana/utils';
strToNumber('42');
// 42
strToNumber('3.14');
// 3.14
strToNumber(100);
// 100 (ya es número, retorna sin cambios)
Con Manejo de Errores
try {
const age = strToNumber('30');
console.log(`Edad: ${age}`);
} catch (error) {
console.error('Edad inválida');
}
try {
const invalid = strToNumber('abc');
} catch (error) {
// Error: abc is not a number
}
Validación de Form Input
function validateAgeInput(input: string): number | null {
try {
const age = strToNumber(input);
if (age < 0 || age > 150) {
throw new Error('Edad fuera de rango');
}
return age;
} catch {
return null;
}
}
const age = validateAgeInput('25');
// 25
const invalid = validateAgeInput('abc');
// null
Procesamiento de Datos de API
interface Product {
id: string;
price: string;
quantity: string;
}
function processProducts(products: Product[]) {
return products.map(product => ({
id: product.id,
price: strToNumber(product.price),
quantity: strToNumber(product.quantity)
}));
}
Query Parameters
function getPageNumber(): number {
const params = new URLSearchParams(window.location.search);
const pageParam = params.get('page');
try {
return strToNumber(pageParam || '1');
} catch {
return 1; // Default a página 1 si es inválido
}
}
CSV Parsing
function parseCSVRow(row: string): number[] {
return row.split(',').map(cell => {
try {
return strToNumber(cell.trim());
} catch {
return 0; // O lanzar error según necesites
}
});
}
parseCSVRow('10, 20, 30, 40');
// [10, 20, 30, 40]
Form Validation
interface PriceInput {
amount: string;
currency: string;
}
function validatePrice(input: PriceInput): { valid: boolean; price?: number } {
try {
const price = strToNumber(input.amount);
if (price <= 0) {
return { valid: false };
}
return { valid: true, price };
} catch {
return { valid: false };
}
}
Calculator Input
function calculate(operation: string, a: string, b: string): number | null {
try {
const num1 = strToNumber(a);
const num2 = strToNumber(b);
switch (operation) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return num1 * num2;
case '/': return num2 !== 0 ? num1 / num2 : null;
default: return null;
}
} catch {
return null;
}
}
Configuration Parsing
interface Config {
port: string;
timeout: string;
maxRetries: string;
}
function parseConfig(config: Config) {
return {
port: strToNumber(config.port),
timeout: strToNumber(config.timeout),
maxRetries: strToNumber(config.maxRetries)
};
}
Range Validation
function validateQuantity(input: string, min: number, max: number): number {
const quantity = strToNumber(input);
if (quantity < min || quantity > max) {
throw new Error(`Cantidad debe estar entre ${min} y ${max}`);
}
return quantity;
}
const qty = validateQuantity('5', 1, 10);
// 5
Casos de Uso Comunes
- Form inputs: Convertir inputs de usuario a números
- API data: Procesar datos numéricos de APIs como strings
- Query parameters: Parsear parámetros de URL
- CSV/Data parsing: Procesar archivos de datos
- Configuration: Parsear configuraciones numéricas
- Validation: Validar inputs numéricos con manejo de errores
- Calculations: Preparar valores para cálculos matemáticos
Comportamiento
Strings Válidos
strToNumber('42'); // 42
strToNumber('3.14'); // 3.14
strToNumber('-10'); // -10
strToNumber('0'); // 0
strToNumber(' 100 '); // 100 (con espacios)
strToNumber('1e3'); // 1000 (notación científica)
strToNumber('0x10'); // 16 (hexadecimal, porque usa Number())
Números como Input
strToNumber(42); // 42
strToNumber(3.14); // 3.14
strToNumber(0); // 0
strToNumber(-10); // -10
Strings Inválidos (Lanzan Error)
strToNumber('abc'); // Error: abc is not a number
strToNumber(''); // Error: is not a number
strToNumber('12abc'); // Error: 12abc is not a number
strToNumber('NaN'); // Error: NaN is not a number
strToNumber(null); // Error: null is not a number
strToNumber(undefined); // Error: undefined is not a number
Notas Técnicas
- Validación: Usa
isNaN(Number(value) - parseFloat(value))para validar - Number(): Convierte usando
Number()constructor - Type checking: Verifica que el resultado sea tipo
number - Error message: El mensaje de error incluye el valor que falló
- Spaces: Maneja espacios automáticamente (trim implícito)
- Decimal separator: Usa punto (
.) como separador decimal
Validación Interna
La función usa la siguiente lógica de validación:
if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {
return Number(value);
}
if (typeof value !== 'number') {
throw new Error(`${value} is not a number`);
}
return value;
Esto verifica:
- Si es string y puede ser convertido a número válido
- Si ya es número, lo retorna directamente
- Si no cumple ninguna condición, lanza error
Limitaciones
A diferencia de parseInt() o parseFloat(), esta función lanza un error si la conversión falla:
// parseInt retorna NaN
parseInt('abc'); // NaN
// strToNumber lanza error
strToNumber('abc'); // ❌ Error: abc is not a number
// Debes manejar el error:
try {
const num = strToNumber(input);
} catch (error) {
// Manejar error
}
La función no maneja formatos numéricos localizados (ej: 1.000,50 en español):
// ❌ No funciona con formato español
strToNumber('1.000,50'); // Error
// ✅ Solo formato internacional (punto decimal)
strToNumber('1000.50'); // 1000.5
// Si necesitas soportar formatos localizados:
function parseLocalizedNumber(value: string, locale: string = 'es-ES'): number {
const normalized = value.replace(',', '.');
return strToNumber(normalized);
}
Valores especiales como 'Infinity' o 'NaN' lanzan error:
strToNumber('Infinity'); // Error
strToNumber('NaN'); // Error
strToNumber(Infinity); // Infinity (acepta número Infinity)
strToNumber(NaN); // NaN (un number se retorna sin validar)
Ver También
- tryJSONParse - Parse seguro de JSON
- hasValue - Validar valores antes de convertir