小数的正则表达式

Regular expression for decimals

您好专家, 我有一个要求,我认为正则表达式可能有助于减少代码中的大量 if 语句和条件。 我的要求是这样的 我有一个显示在 UI( JavaScript) 中的数量字段,它有一个从后端发送的控制因子(基于数量字段的计量单位)。

例如我的数量 = "126.768" 控制因子D = "2"(表示小数点后显示位数为2).

现在我需要一个正则表达式来找到以下

Regex1 应该检查数量是否有任何小数点。如果是这样,那么它应该检查小数点后的值是否不只是零(例如,有时数量没有格式化为小数点的全长 145.000,在我们的例子中应该在 UI 中显示为 145 和不需要考虑控制因子 D)。 RegEx 还应考虑数量值,如“.590”“.001”等

由于我是 RegEx 的新手,所以我很难想出一个表达式

我设法制作了一个非常基本的 RegEx,它只检查“.”。在数量和“。”之后的所有值中 正则表达式 = /[.]\d*/g

如果 RegEx1 returns 是肯定的结果。然后 Regex2 现在应该检查值 D。它应该根据 D 调整小数点。例如,如果 D = 3 和数量 = 345.26,那么 regex2 的输出应该给出 345.260,同样地 D = 1 那么数量应该是 345.3(不知道是否可以使用 RegEx 进行舍入,没有舍入的解决方案也可以)。

此致, 宾斯

第一个正则表达式是

"\d*\.\d*[1-9]\d*"

它在点后搜索至少 1 个非零数字。

对于第二点,只有当数字超过控制因子时才可以用正则表达式舍入,而对于0-padding则不能使用正则表达式:

function round(num, control) {
  var intPart = num.split(".")[0];
  var decPart = num.split(".")[1];
  decPart = decPart.substring(0, control);  //this does the truncation
  var padding = "0".repeat(control - decPart.length); //this does the 0-padding
  return intPart + "." + decPart + padding;
}

var num1 = "210.012";
var num2 = "210.1";
var control = 2;
console.log(round(num1, control));
console.log(round(num2, control));

您不需要任何检查或正则表达式, 有一种 Number.prototype.toFixed 方法可以帮助您调整小数位。

它基本上将 number 舍入到最接近的 decimal point 和 returns 字符串。如果您使用的是字符串,请确保在转换之前(静态使用 Number

console.log(17.1234.toFixed(2)); // round it down
console.log(17.1264.toFixed(2)); // round it up
console.log(17..toFixed(2)); // Integer
console.log(Number("126.768").toFixed(2)); // from string casting