Math

Funciones más comunes

  • La función Math.abs() retorna el valor absoluto de un número.

Math.abs('-1');     // 1
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs('');       // 0
Math.abs([]);       // 0
Math.abs([2]);      // 2
Math.abs([1,2]);    // NaN
Math.abs({});       // NaN
Math.abs('string'); // NaN
Math.abs();         // NaN
  • El método toFixed()(Number.prototype.toFixed()) formatea un número usando notación de punto fijo.

function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// Expected output: "123.46"

console.log(financial(0.004));
// Expected output: "0.00"

console.log(financial('1.23e+5'));
// Expected output: "123000.00"

Remover valores decimales

var v = 3.14; 
console.log(Math.trunc(v));
console.log(Math.round(v));
console.log(Math.floor(v));
console.log(Math.ceil(v));
// prints results for different input values you get these results

//  v        t   r   f   c
//  3.87 : [ 3,  4,  3,  4]
//  3.14 : [ 3,  3,  3,  4]
// -3.14 : [-3, -3, -4, -3]
// -3.87 : [-3, -4, -4, -3]

// Math.trunc() cuts away (truncates) the decimal places.
// Math.round() rounds towards closest integer number.
// Math.floor() rounds towards closest lower integer number. 3.5 -> 3 -3.5 -> -4
// Math.ceil() rounds towards closest higher integer number. 3.5 -> 4 -3.5 -> -3

Last updated