Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda