Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!