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

C#(Xamarin)中使用正则表达式实现货币格式化

How to Auto-Add Commas to Currency Inputs While Typing Using Regex

Great question! Adding dynamic comma formatting to currency inputs makes them much more user-friendly. Here's a practical approach using JavaScript and regex that works seamlessly as the user types:

Step-by-Step Implementation

1. HTML Setup

First, create a text input (avoid type="number" since it doesn't support commas natively):

<input type="text" id="currencyInput" placeholder="$0" autocomplete="off">

2. JavaScript Logic

We'll listen for input events, sanitize the value, apply regex formatting, and maintain proper cursor position (critical for good UX):

const currencyInput = document.getElementById('currencyInput');

currencyInput.addEventListener('input', function(e) {
  // Capture current value and cursor position
  let currentValue = e.target.value;
  const originalCursorPos = e.target.selectionStart;

  // Sanitize input: keep only $ and digits, remove existing commas
  const sanitized = currentValue.replace(/[^$\d]/g, '');
  
  // Split into currency symbol (if present) and numeric part
  const [currencySymbol, rawNumbers] = sanitized.startsWith('$') 
    ? ['$', sanitized.slice(1).replace(/,/g, '')] 
    : ['', sanitized.replace(/,/g, '')];

  // Use regex to add commas every 3 digits from the right
  const formattedNumbers = rawNumbers.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  
  // Combine symbol and formatted number
  const newValue = currencySymbol + formattedNumbers;

  // Calculate new cursor position (adjust for added/removed commas)
  const commasBeforeCursorOld = (currentValue.slice(0, originalCursorPos).match(/,/g) || []).length;
  const commasBeforeCursorNew = (newValue.slice(0, originalCursorPos).match(/,/g) || []).length;
  const adjustedCursorPos = originalCursorPos + (commasBeforeCursorNew - commasBeforeCursorOld);

  // Update input value and restore cursor
  e.target.value = newValue;
  e.target.setSelectionRange(adjustedCursorPos, adjustedCursorPos);
});

3. How the Regex Works

The key regex pattern here is /\B(?=(\d{3})+(?!\d))/g:

  • \B: Matches a non-word boundary (avoids adding a comma at the start of the number)
  • (?=(\d{3})+(?!\d)): A positive lookahead that checks for one or more groups of 3 digits, with no additional digits after them. This ensures commas are inserted from right to left, exactly where needed.

Key Notes for Improvement

  • Support Other Currencies: Modify the sanitization regex to include symbols like €, £, or ¥ (e.g., /[^$€£¥\d]/g)
  • Negative Values: Adjust the logic to handle leading - signs by splitting the symbol, negative sign, and numbers separately
  • Framework Adaptation: For React/Vue, use state to manage the input value and apply the same formatting logic when updating state
  • Paste Handling: The input event automatically handles pasted content, so no extra code is needed for that

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:01:09