Search code examples
javascriptparsefloat

Remove trailing zeroes to 2 decimal positions


I would like your help with the following: I have prices which could be more then 2 decimal points, i.e. 0.009 or 0.0014

However, I also have prices which have regular prices like 2.9 or 14.45.

I store all prices up until 4 decimal points i.e. 2.9 becomes 2.9000.

What I'm looking for is the following, I want to show at least 2 decimal points num.toFixed(2), however if there are more then 2 decimal points and those are not 0 I want to show them too.

Example:

  • 2.9000 becomes 2.90
  • 0.0001 remains 0.0001
  • 2.8540 becomes 2.854
  • 1.0100 becomes 1.01
  • 3.0000 becomes 3.00

I've tried num.toFixed(2) but this removes all decimals after the 2nd.

How can I achieve what I've shown in the example?

Thanks in advance!


Solution

  • Shorten it regardless and only return the new number if it has the same value as the original.

    function shortenOrReturn(num) {
      var shortNum = num.toFixed(2);
      return (shortNum == num) ? shortNum : num;
    }
    
    console.log(shortenOrReturn(2.9000)) // becomes 2.90
    console.log(shortenOrReturn(0.0001)) // remains 0.0001
    console.log(shortenOrReturn(2.8540)) // becomes 2.854
    console.log(shortenOrReturn(1.0100)) // becomes 1.01
    console.log(shortenOrReturn(3.0000)) // becomes 3.00