如何在 html 输入中同时支持逗号和点并固定 2 位小数位并使用空格作为千位分隔符

问题描述 投票:0回答:2

如何在 html 输入中同时支持逗号和点,并在按键事件上使用 javascript 将小数位固定为 2 位并使用空格作为千位分隔符。

html input decimal separator
2个回答
0
投票

如果您从键盘输入,而不是剪贴板粘贴:

<!DOCTYPE html>
<html>
<head>
    <title>Input Field with Comma and Dot Support</title>
</head>
<body>
    <label for="myInput">Enter a number:</label>
    <input type="text" id="myInput">

<script>
  document.getElementById("myInput").addEventListener("input", function(event) {
    // Get input value
    let input = event.target.value;
    
    // Remove all non-numeric characters except decimal point
    input = input.replace(/[^\d.]/g, '');
    
    // Only allow one decimal point
    let decimalIndex = input.indexOf('.');
    if (decimalIndex !== -1) {
      input = input.substr(0, decimalIndex + 1) + input.substr(decimalIndex + 1).replace(/\./g, '');
      
      // Limit to two decimal places
      input = input.substr(0, decimalIndex + 3);
    }
    
    // Insert comma after every third digit from the end
    input = input.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    
    // Update input value
    event.target.value = input;
  });
</script>
<p>With this code, you should be able to input 185656.56 and have it formatted as 1,856,56.56</p>
</body>
</html>


0
投票

如果您从剪贴板粘贴输入:

<input type="text" id="myInput" oninput="formatNumber()" />

<script>
function formatNumber() {
  // Get the current value of the input field
  const input = document.getElementById("myInput");
  let value = input.value;

  // Check if the value is empty or not a number
  if (value === "" || isNaN(parseFloat(value))) {
    // If so, set the value to 0
    value = "0";
  }

  // Replace commas with periods
  value = value.replace(/,/g, ".");

  // Parse the numeric value
  let number = parseFloat(value);

  // Format the number with a space as a thousand separator and two decimal places
  value = number.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});

  // Update the input field with the formatted value
  input.value = value;
}
</script>

© www.soinside.com 2019 - 2024. All rights reserved.