You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery的onchange/keyup事件限制输入框保留两位小数

Auto-Format Input to 2 Decimal Places (Truncated) with jQuery

Hey there, here's a practical solution to automatically format input values to exactly two decimal places (truncating any extra digits, like turning 54.78987 into 54.78) using jQuery's keyup and change events. This handles real-time input, pasted values, and invalid characters gracefully.


Step 1: HTML Input Element

First, set up your input field:

<input type="text" id="decimalInput" placeholder="Enter a number (e.g., 54.78987)">

Step 2: jQuery Implementation

Add this script to handle the formatting logic:

$(document).ready(function() {
  // Target the input field
  const $decimalInput = $('#decimalInput');

  // Helper function to clean and format the input value
  function truncateToTwoDecimals(inputValue) {
    // Remove all non-numeric characters except dots and negative signs
    let cleanedValue = inputValue.replace(/[^0-9.-]/g, '');
    
    // Ensure only one decimal point exists (prevents multiple dots)
    cleanedValue = cleanedValue.replace(/(\..*)\./g, '$1');
    
    // Convert to a number; if invalid, return the cleaned value
    const num = parseFloat(cleanedValue);
    if (isNaN(num)) return cleanedValue;

    // Truncate to 2 decimal places (no rounding)
    const truncatedNum = Math.floor(num * 100) / 100;
    
    // Return as a string with exactly 2 decimal places (e.g., 54 → "54.00")
    return truncatedNum.toFixed(2);
  }

  // Bind events to trigger formatting
  $decimalInput.on('keyup change', function() {
    const currentValue = $(this).val();
    const formattedValue = truncateToTwoDecimals(currentValue);
    
    // Only update the value if it changed to avoid infinite loops
    if (formattedValue !== currentValue) {
      $(this).val(formattedValue);
    }
  });
});

Key Details & Customization Tips

  • Truncation vs. Rounding: The current code truncates extra decimals (54.78987 → 54.78). If you want to round instead, replace the truncation line with const roundedNum = num.toFixed(2); (this will turn 54.78987 into 54.79).
  • Invalid Character Filtering: The regex [^0-9.-] removes any characters that aren't numbers, dots, or negative signs, so users can't type letters or symbols.
  • Multiple Decimal Points: The regex (\..*)\./g ensures only one decimal point is kept (e.g., "12..34" becomes "12.34").
  • Event Coverage: Using both keyup (real-time typing) and change (pasting values or losing focus) ensures all input scenarios are handled.

内容的提问来源于stack exchange,提问作者onlinegsali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:57:32