Conversiones de tipos de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos

  • Convertir cadenas en números

  • Convertir números en cadenas

  • Convertir fechas en números

  • Convertir números en fechas

  • Convertir booleanos a números

  • Convertir números a booleanos

Conversión de tipo JavaScript

Las variables de JavaScript se pueden convertir en una nueva variable y otro tipo de datos:

  • Mediante el uso de una función de JavaScript

  • Automáticamente por el propio JavaScript


Convertir cadenas en números

El método global Number() convierte una variable (o un valor) en un número.

Una cadena numérica (como "3.14") se convierte en un número (como 3.14).

Una cadena vacía (como "") se convierte en 0.

Una cadena no numérica (como "John") se convierte en NaN (no es un número).

Ejemplos

Estos convertirán:

Number("3.14")
Number(Math.PI)
Number(" ")
Number("")

Estos no se convertirán:

Number("99 88")
Number("John")

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The Number() Method</h2>

<p>The Number() metod converts a variable (or value) into a number:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Number("3.14") + "<br>" +
Number(Math.PI) + "<br>" +
Number("    ") + "<br>" +
Number("") + "<br>" +
Number("99 88") + "<br>" +
Number("John") + "<br>";
</script>

</body>
</html>

Métodos numéricos

En el capítulo Métodos numéricos, usted encontrará más métodos que se pueden utilizar para convertir cadenas a números:

Method

Descripción

Number()

Devuelve un número, convertido a partir de su argumento.

parseFloat()

Analiza una cadena y devuelve un número de punto flotante

parseInt()

Analiza una cadena y devuelve un número entero


El operador unario +

El operador unario + se puede utilizar para convertir una variable a un número:

Ejemplo

let y = "5";     
// y is a string
let x = + y;      
// x is a number

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>The JavaScript typeof Operator</h2>

<p>The typeof operator returns the type of a variable or expression:</p>

<p id="demo"></p>

<script>
let y = "5";
let x = + y;
document.getElementById("demo").innerHTML = typeof y + "<br>" + typeof x;
</script>

</body>
</html>


Si el La variable no se puede convertir, seguirá convirtiéndose en un número, pero con el valor NaN (No un número):

Ejemplo

let y = "John";  
// y is a string
let x = + y;      // x is a number (NaN)

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>The JavaScript typeof Operator</h2>

<p>The typeof operator returns the type of a variable or expression:</p>

<p id="demo"></p>

<script>
let y = "John";
let x = + y;
document.getElementById("demo").innerHTML = typeof y + "<br>" + typeof x;
</script>

</body>
</html>




Convertir números en cadenas

El método global String() puede convertir números en cadenas.

Se puede utilizar en cualquier tipo de números, literales, variables o expresiones:

Ejemplo

String(x)         // returns a string from a number variable x
 String(123)       // returns a string from a number literal 123
 String(100 + 23)  // returns a string from a number from an expression

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>The JavaScript String() Method</h2>

<p>The String() method can convert a number to a string.</p>

<p id="demo"></p>

<script>
let x = 123;
document.getElementById("demo").innerHTML =
  String(x) + "<br>" +
  String(123) + "<br>" +
  String(100 + 23);
</script>
</body>
</html>

El método numérico toString() hace lo mismo.

Ejemplo

x.toString()
(123).toString()
(100 + 23).toString()

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toString() method converts a number to a string.</p>

<p id="demo"></p>

<script>
let x = 123;
document.getElementById("demo").innerHTML =
  x.toString() + "<br>" +
   (123).toString() + "<br>" +
   (100 + 23).toString();
</script>

</body>
</html>

Más métodos

En el capítulo Métodos numéricos, usted encontrará más métodos que se pueden utilizar para convertir números a instrumentos de cuerda:

toExponential()

Devuelve una cadena, con un número redondeado y escrito usando notación exponencial.

toFixed()

Devuelve una cadena, con un número redondeado y escrito con un número específico de decimales.

toPrecision()

Devuelve una cadena, con un número escrito con una longitud especificada


Convertir fechas en números

El método global Number() se puede utilizar para convertir fechas a números.

d = new Date();
Number(d)          // returns 1404568027739

El método de fecha getTime() hace lo mismo.

d = new Date();
d.getTime()        // returns 1404568027739

Convertir fechas en cadenas

El método global String() puede convertir fechas a instrumentos de cuerda.

 String(Date())  // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"

El método Date toString() hace lo mismo.

Ejemplo

 Date().toString()  // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"

En el capítulo Métodos de fecha, usted encontrará más métodos que se pueden utilizar para convertir fechas a instrumentos de cuerda:

getDate()

Obtener el día como un número (1-31)

getDay()

Obtener el día de la semana un número (0-6)

getFullYear()

Obtenga el año de cuatro dígitos (aaaa)

getHours()

Obtener la hora (0-23)

getMilliseconds()

Obtenga los milisegundos (0-999)

getMinutes()

Obtener los minutos (0-59)

getMonth()

Obtener el mes (0-11)

getSeconds()

Obtener los segundos (0-59)

getTime()

Obtenga la hora (milisegundos desde el 1 de enero de 1970)


Convertir booleanos a números

El método global Number() también puede convertir valores booleanos en números.

Number(false)     // returns 0
Number(true)      // returns 1

Convertir booleanos en cadenas

El método global String() puede convertir valores booleanos a instrumentos de cuerda.

String(false)      // returns "false"
String(true)       // returns "true"

El método booleano toString() hace lo mismo.

false.toString()   // returns "false"
  true.toString()    // returns "true"

Conversión automática de tipos

Cuando JavaScript intenta operar con un tipo de datos "incorrecto", intentará convierta el valor a un tipo "correcto".

El resultado no siempre es el esperado:

5 + null    // returns 5         because null is converted to 0
"5" + null  // returns "5null"   because null is converted to "null"
"5" + 2     // returns 
    "52"      because 2 is converted to "2"
 "5" - 2     // returns 3         because "5" is converted to 5
"5" * "2"   // returns 
    10        because "5" and "2" are 
    converted to 5 and 2

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
(5 + null) + "<br>"  +
("5" + null) + "<br>" +
("5" + 2) + "<br>" +
("5" - 2) + "<br>" +
("5" * "2") + "<br>" +
("5" / "2") + "<br>"
</script>

</body>
</html>



Conversión automática de cadenas

JavaScript llama automáticamente a la función toString() de la variable cuando intenta para "generar" un objeto o una variable:

document.getElementById("demo").innerHTML = myVar;

// if myVar = {name:"Fjohn"}  // toString converts to "[object Object]"
// if myVar = [1,2,3,4]       // toString converts to "1,2,3,4"
// if myVar = new Date()      // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"

También se convierten números y valores booleanos, pero esto no es muy visible:

// if myVar = 123             // toString converts to "123"
// if myVar = true            // toString converts to "true"
// if myVar = false           // toString converts to "false"

Tabla de conversión de tipos de JavaScript

Esta tabla muestra el resultado de convertir diferentes valores de JavaScript a Número, Cadena y Booleano:


Valor original:

false

Convertido a número:

0

Convertido a cadena:

"false"

Convertido a booleano:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting false to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = false;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

true

Convertido a número:

1

Convertido a cadena:

"true"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting true to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = true;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

0

Convertido a número:

0

Convertido a cadena:

"0"

Convertido a booleano:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting the number 0 to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = 0;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

1

Convertido a número:

1

Convertido a cadena:

"1"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting the number 1 to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = 1;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

"0"

Convertido a número:

0

Convertido a cadena:

"0"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting the string "0" to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = "0";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

"000"

Convertido a número:

0

Convertido a cadena:

"000"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting the string "000" to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = "000";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

"1"

Convertido a número:

1

Convertido a cadena:

"1"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting the string "1" to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = 1;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

NaN

Convertido a número:

NaN

Convertido a cadena:

"NaN"

Convertido a booleano:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting NaN to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = NaN;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

Infinity

Convertido a número:

Infinity

Convertido a cadena:

"Infinity"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting Infinity to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = Infinity;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

-Infinity

Convertido a número:

-Infinity

Convertido a cadena:

"-Infinity"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting -Infinity to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = -Infinity;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

""

Convertido a número:

0

Convertido a cadena:

""

Convertido a booleano:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting an empty string to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = "";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

"20"

Convertido a número:

20

Convertido a cadena:

"20"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting a numeric string to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = "20";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

NaN

Convertido a número:

"twenty"

Convertido a cadena:

"twenty"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting a text string to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = "twenty";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

[ ]

Convertido a número:

0

Convertido a cadena:

""

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<p>Converting an empty array to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
var x = [];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

[20]

Convertido a número:

20

Convertido a cadena:

"20"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<p>Converting an array with one numeric element to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
var x = [20];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

[10,20]

Convertido a número:

NaN

Convertido a cadena:

"10,20"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<p>Converting an array with two numeric elements to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
var x = [10,20];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

["twenty"]

Convertido a número:

NaN

Convertido a cadena:

"twenty"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<p>Converting an array with one string element to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
var x = ["twenty"];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

["ten","twenty"]

Convertido a número:

NaN

Convertido a cadena:

"ten,twenty"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<p>Converting an array with two string element to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
var x = ["ten","twenty"];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

function(){}

Convertido a número:

NaN

Convertido a cadena:

"function(){}"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting a function to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
const x = function(){};
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

{ }

Convertido a número:

NaN

Convertido a cadena:

"[object Object]"

Convertido a booleano:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting an object to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
const x = {};
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

null

Convertido a número:

0

Convertido a cadena:

"null"

Convertido a booleano:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting null to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = null;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>



Valor original:

undefined

Convertido a número:

NaN

Convertido a cadena:

"undefined"

Convertido a booleano:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting undefined to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = undefined;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>


Los valores entre comillas indican valores de cadena.

Los valores rojos indican valores que (algunos) programadores podrían no esperar.