使用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
(\..*)\./gensures only one decimal point is kept (e.g., "12..34" becomes "12.34"). - Event Coverage: Using both
keyup(real-time typing) andchange(pasting values or losing focus) ensures all input scenarios are handled.
内容的提问来源于stack exchange,提问作者onlinegsali
相关产品推荐
相关产品推荐

