Search code examples
javascriptnumber-formattingzapier

Zapier - Javascript wrong custom function behaviour


I defined a function numberFormat in my Zapier app

I was expecting a result like 50 but actually I get 5000. Any suggestions about how to solve this?

function numberFormat(number) {
  var newString = number.toString().replace(/,/g, '.'); // togli tutte le virgole e sostituiscile con punti
  var lastDotIndex = newString.lastIndexOf('.'); // l'ultimo che trovi è separatore dei decimali
  var decimal = newString.slice(lastDotIndex); // parte decimale
  var integerSlice = newString.slice(0, lastDotIndex); // parte intera
  var integer = integerSlice.replace(/[^0-9]/g, ''); // della parte intera mi servono solo i numeri
  var strResult = integer + decimal; // concatena intero e decimale

  return Number(strResult);
}

// In this same environment I sent a test value like this:

console.log(numberFormat("50,00"));


Solution

  • You need to add a dot or just take the replacements and get a number from it.

    function numberFormat(number) {
        return +number
            .toString()
            .replace(/,/g, '.')
            .replace(/\.(?=.*\.)/g, '')
            .replace(/[^0-9.]/g, ''); // allow dot
    }
    
    console.log(numberFormat("50,00"));
    console.log(numberFormat("1,000,00"))