skip to Main Content

How can I support both Comma and Dot in html input and fix the decimal place for 2 digits and use a space for thousand separator using javascript on keypress event.

2

Answers


  1. If you make an input from clipboard paste:

    <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>
    Login or Signup to reply.
  2. If you make an input from keyboard, not clipboard paste:

    <!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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search