首页 > 解决方案 > Zapier - Javascript错误的自定义函数行为

问题描述

我在我的 Zapier 应用程序中定义了一个函数 numberFormat

我期待一个结果,50但实际上我得到了5000。关于如何解决这个问题的任何建议?

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"));

标签: javascriptnumber-formattingzapier

解决方案


您需要添加一个点或只是替换并从中获取一个数字。

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"))


推荐阅读