Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
Javascript | floating point numbers

When assigning 2 variables with decimal point numbers and calculating the sum of both of them when using console.log() to return the result if they equal the whole number they return it without the decimal point.

For example

 let num1 = 2.2;
 let num2 = 2.8;
console.log(num1 + num2 )

returns 5 when I require 5.0 to be returned.

I've tried toFixed(1) but the test requires various numbers to be returned

For example

let num1 = 2.22
 let num2 = 2.71
console.log((num1 + num2)toFixed(1))

returns 4.9 when I require 4.93

Is there a way I can assign the variable a floating-point decimal and keep its status even in the return value is a whole number?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The thing is you don't know how many decimal place there is before the addition.

So assuming you would like to keep the longuest amount of decimal places, you could write a function like this:

function decimalPlaces(arr) {
  return Math.max(...arr.map(n => n.toString().split(".")[1].length))
}

console.log((2.8 + 2.2).toFixed(decimalPlaces([2.8, 2.2])))

console.log((2.22 + 2.71).toFixed(decimalPlaces([2.22, 2.71])))

console.log((1.7 + 1.3001).toFixed(decimalPlaces([1.7, 1.3001])))

But notice that you have to pass the original numbers to the function in an array... Up to you to decide if it's useful.

about 4 years ago · Juan Pablo Isaza Denunciar

0

function add(num1, num2) {
    const num1PointLength = String(num1).split(".")[1]?.length || 0;
    const num2PointLength = String(num2).split(".")[1]?.length || 0;
    return (num1 + num2).toFixed(num1PointLength > num2PointLength ? num1PointLength : num2PointLength);
}

let num1 = 2.2;
let num2 = 2.8;

console.log(add(num1, num2));

about 4 years ago · Juan Pablo Isaza Denunciar

0

toFixed()-> this method rounds the string to a specified number of decimals.If the number of decimals are higher than in the number, zeros are added.


let num1 = 2.2
let num2 = 2.8
console.log((num1 + num2).toFixed(1))

returns=> 5.0

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda