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

122
Views
How to validate a number has a 2 decimal place precision with javaScript?

I'm trying to check if a number has a 2 decimal place precision. I know how to convert a number to a 2 decimal place precision like this:

var myNumber = 2.456;
var currentNumber = parseFloat(myNumber);
currentNumber = currentNumber.toFixed(2); 
console.log(currentNumber); 

so If I enter:

  • 1 this will turn into 1.00
  • 2.457 this will turn into 2.46

but how can I check if the result of my code has a 2 decimal place precision? Thanks a lot in advance!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Parse the number into a string, split by a period and check whether the second item's length is 2:

function isPrecise(num){
  return String(num).split(".")[1]?.length == 2;
}

console.log(isPrecise(1.23))
console.log(isPrecise(1.2))
console.log(isPrecise(1))
console.log(isPrecise("1.23")) //works if its a string too

You can also use a regex:

function isPrecise(num){
  return /\d+\.\d{2}/gm.test(String(num));
}

console.log(isPrecise(1.23))
console.log(isPrecise(1.2))
console.log(isPrecise("1.23")) //works if its a string too

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!