Remove digits representing irrelevant precision from a number with JavaScript

I’m looking for a function in Javascript (or JQuery) to remove digits representing irrelevant precision from a number. I’m calculating an estimated probability, and it could be a range of values – and the exact decimal isn’t very relevant – just the first non-zero decimal from the left.

  • Such as 0.0001, in which case that’s what I want to display.
  • But if it’s 0.2453535 – I just want to show 0.2.
  • Or if it’s 0.015 – I just want to round to display 0.02
  • Or if it’s 0.00412 – I just want to round to display 0.004

Any thoughts on a good way to accomplish that?

Answer

That one is not as simple as it looks.

I assumed it has to also work on non-float and negative numbers. Here is a one liner… Fell free for questions as I don’t know what to explain here.

EDIT

The nice one liner is getting a bit more complex due to the 0.0105 => 0.011 case mentionned in comments.

2nd EDIT

To round the last decimal if neded just defaced my initial “one liner” solution. But now that should be exact. I am opened for additionnal test cases 😉

3rd EDIT

I added the “Not A Number” case.

function formatNumber(x){
  
  if(isNaN(x)){return NaN}
  
  let prev = "0"
  let toFixedParam = (""+x).split(".")[1]?.split("").filter(n=>{
    let issignificativeZero = (n=="0" && prev =="0")
    prev = n
    return issignificativeZero
  }).length+1
  
  let result =  parseFloat(x.toFixed(toFixedParam))
  
  
  // Should the last number be rounded? (The 0.015 case).
  let nextNum = parseInt(x.toString().replace(result,"").slice(0,1)) 
  if(nextNum>=5){
    let factor = Math.pow(10,toFixedParam)
    result = Math.round(parseFloat("" + result + nextNum) * factor) / factor
  }
  
  return result
}

// You test cases
console.log(formatNumber(0.0001))
console.log(formatNumber(0.2453535))
console.log(formatNumber(0.015),"========= should rounded to 0.02")
console.log(formatNumber(0.00412))

// Negative numbers
console.log(formatNumber(-2.01))
console.log(formatNumber(-0.0045))

// Non float numbers
console.log(formatNumber(4))
console.log(formatNumber(102))

// The 0.011 case mentionned in comments
console.log(formatNumber(0.0105))

// The Not A Number case
console.log(formatNumber("Hello"))

Leave a Reply

Your email address will not be published. Required fields are marked *