MVC 6 Razor页面千分位分隔符NaN/Infinity问题及小数补全需求
Fixed Solution for Number Formatting in MVC 6 Razor Pages
Here's the corrected code that addresses all three issues:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $(function () { $("#TransAmount").on('keyup', function () { let rawValue = $(this).val().replace(/,/g, ''); // Handle empty input to avoid NaN if (!rawValue) { $(this).val(''); return; } let num = parseFloat(rawValue); // Skip formatting for non-finite numbers to avoid Infinity if (!isFinite(num)) { $(this).val(rawValue); return; } $(this).val(formatNumber(num)); }); }); function formatNumber(num) { const fixedNum = num.toFixed(2); const [integerPart, decimalPart] = fixedNum.split('.'); const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ','); return `${formattedInteger}.${decimalPart}`; } </script>
Key Fixes Explained:
- Eliminates NaN on empty input: Checks if the cleaned input is empty and clears the field instead of attempting to parse an invalid value.
- Prevents Infinity for large numbers: Uses
isFinite()to validate the parsed number; if invalid, retains the raw input rather than formatting to Infinity. - Adds two decimal places: Uses
toFixed(2)to enforce two decimal digits, then applies thousand separators only to the integer portion of the number, ensuring consistent formatting like10,000.00.
Optional Improvement:
Replace the keyup event with the input event to handle all input methods (paste, drag-and-drop, etc.) more reliably:
$("#TransAmount").on('input', function () { // ... same logic as before });
内容的提问来源于stack exchange,提问作者JPeter
相关产品推荐
相关产品推荐

