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

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 like 10,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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:52:43