java格式化BigDecimal為#,###,##0.00

Java BigDecimal 格式化工具

我将为您创建一个Java BigDecimal格式化工具,实现将数字格式化为"#,###,##0.00"格式。这个界面允许用户输入数字并查看格式化结果。

设计思路

  • 创建简洁直观的输入界面

  • 实现实时格式化功能

  • 展示格式化前后的对比

  • 添加格式化规则说明

完整实现代码

复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Java BigDecimal 格式化工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            width: 100%;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #3498db 0%, #2c3e50 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 16px;
        }
        
        .content {
            padding: 30px;
        }
        
        .input-section {
            margin-bottom: 30px;
        }
        
        .input-group {
            display: flex;
            margin-bottom: 20px;
        }
        
        input {
            flex: 1;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px 0 0 8px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s;
        }
        
        input:focus {
            border-color: #3498db;
        }
        
        button {
            background: #3498db;
            color: white;
            border: none;
            padding: 0 20px;
            border-radius: 0 8px 8px 0;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }
        
        button:hover {
            background: #2980b9;
        }
        
        .result-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        
        .result-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #2c3e50;
        }
        
        .formatted-result {
            font-size: 24px;
            font-weight: 700;
            color: #27ae60;
            padding: 15px;
            background: white;
            border-radius: 8px;
            text-align: center;
            border: 2px dashed #e0e0e0;
        }
        
        .examples-section {
            margin-bottom: 30px;
        }
        
        .examples-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #2c3e50;
        }
        
        .examples-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
        }
        
        .example-item {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #3498db;
        }
        
        .example-original {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 5px;
        }
        
        .example-formatted {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        .info-section {
            background: #e8f4fc;
            padding: 20px;
            border-radius: 8px;
        }
        
        .info-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #2c3e50;
        }
        
        .info-content {
            line-height: 1.6;
            color: #34495e;
        }
        
        .info-content ul {
            padding-left: 20px;
            margin: 10px 0;
        }
        
        .info-content li {
            margin-bottom: 8px;
        }
        
        .code-block {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            margin: 15px 0;
            overflow-x: auto;
        }
        
        @media (max-width: 600px) {
            .input-group {
                flex-direction: column;
            }
            
            input {
                border-radius: 8px;
                margin-bottom: 10px;
            }
            
            button {
                border-radius: 8px;
                padding: 12px;
            }
            
            .examples-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Java BigDecimal 格式化工具</h1>
            <p>将数字格式化为 #,###,##0.00 格式</p>
        </div>
        
        <div class="content">
            <div class="input-section">
                <div class="input-group">
                    <input type="text" id="numberInput" placeholder="输入数字(例如:1234567.89)">
                    <button id="formatBtn">格式化</button>
                </div>
            </div>
            
            <div class="result-section">
                <div class="result-title">格式化结果:</div>
                <div class="formatted-result" id="formattedResult">-,---,--0.00</div>
            </div>
            
            <div class="examples-section">
                <div class="examples-title">示例:</div>
                <div class="examples-grid" id="examplesGrid">
                    <!-- 示例将通过JavaScript动态生成 -->
                </div>
            </div>
            
            <div class="info-section">
                <div class="info-title">Java 代码实现</div>
                <div class="info-content">
                    <p>在Java中,可以使用以下代码将BigDecimal格式化为<code>#,###,##0.00</code>格式:</p>
                    
                    <div class="code-block">
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class BigDecimalFormatter {
    public static String formatBigDecimal(BigDecimal number) {
        DecimalFormat df = new DecimalFormat("#,###,##0.00");
        return df.format(number);
    }
    
    public static void main(String[] args) {
        BigDecimal num = new BigDecimal("1234567.89");
        String formatted = formatBigDecimal(num);
        System.out.println(formatted); // 输出: 12,34,567.89
    }
}
                    </div>
                    
                    <p>格式化模式说明:</p>
                    <ul>
                        <li><code>#</code> - 数字占位符,不显示多余的零</li>
                        <li><code>0</code> - 数字占位符,显示多余的零</li>
                        <li><code>,</code> - 分组分隔符(千位分隔符)</li>
                        <li><code>.##</code> - 小数部分,保留两位小数</li>
                    </ul>
                    
                    <p>注意:此格式化模式遵循印度数字分组系统,其中数字按千、十万等单位分组。</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const numberInput = document.getElementById('numberInput');
            const formatBtn = document.getElementById('formatBtn');
            const formattedResult = document.getElementById('formattedResult');
            const examplesGrid = document.getElementById('examplesGrid');
            
            // 示例数据
            const examples = [
                { original: '1234567.89', formatted: '12,34,567.89' },
                { original: '987654321.12', formatted: '98,76,54,321.12' },
                { original: '1000.5', formatted: '1,000.50' },
                { original: '123.456', formatted: '123.46' },
                { original: '1234', formatted: '1,234.00' },
                { original: '0.123', formatted: '0.12' }
            ];
            
            // 生成示例
            examples.forEach(example => {
                const exampleItem = document.createElement('div');
                exampleItem.className = 'example-item';
                exampleItem.innerHTML = `
                    <div class="example-original">${example.original}</div>
                    <div class="example-formatted">${example.formatted}</div>
                `;
                examplesGrid.appendChild(exampleItem);
            });
            
            // 格式化函数
            function formatNumber(value) {
                // 移除所有非数字字符(除了小数点和负号)
                const cleanedValue = value.replace(/[^\d.-]/g, '');
                
                // 如果是空值或无效值,返回默认格式
                if (!cleanedValue || isNaN(parseFloat(cleanedValue))) {
                    return '-,---,--0.00';
                }
                
                // 将值转换为数字
                const num = parseFloat(cleanedValue);
                
                // 实现印度数字分组系统
                const parts = Math.abs(num).toFixed(2).split('.');
                let integerPart = parts[0];
                const decimalPart = parts[1];
                
                // 处理整数部分的分组
                let lastThree = integerPart.substring(integerPart.length - 3);
                const otherNumbers = integerPart.substring(0, integerPart.length - 3);
                
                if (otherNumbers !== '') {
                    // 每两位数字添加逗号
                    lastThree = ',' + lastThree;
                    let formattedOther = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",");
                    integerPart = formattedOther + lastThree;
                }
                
                // 添加符号和小数部分
                let result = (num < 0 ? '-' : '') + integerPart + '.' + decimalPart;
                
                return result;
            }
            
            // 格式化按钮点击事件
            formatBtn.addEventListener('click', function() {
                const inputValue = numberInput.value.trim();
                const formatted = formatNumber(inputValue);
                formattedResult.textContent = formatted;
            });
            
            // 输入框回车事件
            numberInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    formatBtn.click();
                }
            });
            
            // 初始示例
            formattedResult.textContent = formatNumber('1234567.89');
        });
    </script>
</body>
</html>

功能说明

这个工具提供了以下功能:

  1. 数字格式化:将输入的数字格式化为 #,###,##0.00 格式

  2. 实时预览:输入数字后点击"格式化"按钮查看结果

  3. 示例展示:提供多个格式化示例供参考

  4. Java代码:展示如何在Java中实现相同的格式化功能

使用说明

  1. 在输入框中输入要格式化的数字

  2. 点击"格式化"按钮或按Enter键查看结果

  3. 格式化结果将显示在结果区域

  4. 可以参考下方的示例了解不同数字的格式化效果

这个工具模拟了Java中使用DecimalFormat类格式化BigDecimal数字的效果,特别是实现了印度数字分组系统(千、十万等单位分组)。

相关推荐
Seven972 小时前
剑指offer-36、两个链表的第⼀个公共节点
java
helloworddm2 小时前
Java和.NET的核心差异
java·开发语言·.net
SimonKing2 小时前
为什么0.1 + 0.2不等于0.3?一次讲透计算机的数学“Bug”
java·数据库·后端
学习编程的Kitty2 小时前
JavaEE初阶——JUC的工具类和死锁
java·开发语言
chinesegf2 小时前
[特殊字符] 常用 Maven 命令
java·spring boot·maven
做运维的阿瑞2 小时前
Redis 高可用集群部署实战:单Docker实现1主2从3
java·redis·docker
小松の博客2 小时前
Mybatis 注解开发
java·tomcat·mybatis
爱吃烤鸡翅的酸菜鱼2 小时前
Java【缓存设计】定时任务+分布式锁实战:Redis vs Redisson实现状态自动扭转以及全量刷新预热机制
java·redis·分布式·缓存·rabbitmq
yugi9878382 小时前
MyBatis框架如何处理字符串相等的判断条件
java·开发语言·tomcat