Add .00 (toFixed) only if number has less than two decimal places

Here you go:

function addZeroes(num) {
// Convert input string to a number and store as a variable.
    var value = Number(num);      
// Split the input string into two arrays containing integers/decimals
    var res = num.split(".");     
// If there is no decimal point or only one decimal place found.
    if(res.length == 1 || res[1].length < 3) { 
// Set the number to two decimal places
        value = value.toFixed(2);
    }
// Return updated or original number.
return value;
}

// If you require the number as a string simply cast back as so
var num = String(value);

See fiddle for demonstration.

edit: Since I first answered this, javascript and I have progressed, here is an improved solution using ES6, but following the same idea:

function addZeroes(num) {
  const dec = num.split('.')[1]
  const len = dec && dec.length > 2 ? dec.length : 2
  return Number(num).toFixed(len)
}

Updated fiddle

edit 2: Or if you are using optional chaining you can do it in one line like so:

const addZeroes = num => Number(num).toFixed(Math.max(num.split('.')[1]?.length, 2) || 2)

Updateder fiddle

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)