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

249
Views
How to format number to have n whole and decimal digits?

Say I have a float x that has a whole part a and decimal part b i.e. x = a.b. How can I format x in JavaScript such that it'll have at most n digits, as shown below:

const n = 5
format(123.0) == '123'
format(123.01) == '123.01'
format(123.012) == '123.01'
format(0.0123) == '0.0123'
format(0.01234) == '0.0123'
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Based on a recently deleted answer that had the logic but didn't really work, I came up with this solution:

const format = (number, digits = 5) => {

  const str = number + ''; // convert to string
  let [integer, decimal] = str.split('.'); // split by dot delimiter

  const integerDigits = integer.length;

  if (integerDigits >= digits) {
    return integer;
  } else {
    let decimalDigits = digits - integerDigits;
    decimal = Number('0.' + decimal.substring(0, decimalDigits)).toString();
    return integer + '.' + decimal.split('.')[1];
  }
}
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!