java数据格式处理

概述

记录一下常用的数据格式处理。千分位分隔符、四舍五入。

代码

复制代码
/**
 * 数据格式化工具类
 * @author **
 * @since **
 */
public class DataFormatUtil {

    private DataFormatUtil() {
        throw new IllegalStateException("工具类不要实例化");
    }

    public static String format(Double value){
        return format(value, 2);
    }

    public static String format(BigDecimal value){
        return format(value, 2);
    }

    /**
     * 千分位分隔符,四舍五入,保留位数
     * @param value 数值
     * @param scale 保留小数位数
     * @return 格式化后的数值
     */
    public static String format(BigDecimal value, int scale){
        if(value == null){
            return "";
        }

        if(scale < 0){
            throw new IllegalArgumentException("保留小数位数不能小于0");
        }

        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setGroupingSeparator(',');
        symbols.setDecimalSeparator('.');
        DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", symbols);
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        decimalFormat.setMinimumFractionDigits(scale);
        decimalFormat.setMaximumFractionDigits(scale);

        return decimalFormat.format(value);
    }

    /**
     * 千分位分隔符,四舍五入,保留位数
     * @param value 数值
     * @param places 保留小数位数
     * @return 格式化后的数值
     */
    public static String format(Double value, int places) {
        if(value == null){
            return "";
        }

        if(places < 0){
            throw new IllegalArgumentException("保留小数位数不能小于0");
        }

        DecimalFormat decimalFormat = new DecimalFormat((places == 0 ? "#,##0" : "#,##0.") + StringUtils.repeat("0", places));
        return decimalFormat.format(value);
    }

}
相关推荐
立志成为大牛的小牛15 分钟前
数据结构——五十一、散列表的基本概念(王道408)
开发语言·数据结构·学习·程序人生·算法·散列表
百***06011 小时前
五大消息模型介绍(RabbitMQ 详细注释版)
java·rabbitmq·java-rabbitmq
转转技术团队1 小时前
MyBatis-Plus踩坑血泪史:那些年我们踩过的坑!
java·面试·mybatis
sg_knight2 小时前
IntelliJ IDEA 实用插件:GitToolBox 使用指南
java·ide·git·intellij-idea·插件·gittoolbox
青云交2 小时前
Java 大视界 -- Java 大数据机器学习模型在电商用户画像构建与精准营销中的应用
java·大数据·机器学习·电商·协同过滤·用户画像·精准营销
明知道的博客2 小时前
解决WSL环境下DeepSeek-OCR运行时内存不足问题
python·ocr·deepseek·deepseek-ocr
z***67772 小时前
Spring EL 表达式的简单介绍和使用
java·后端·spring
机灵猫2 小时前
java锁:从 Mark Word 锁升级到 AQS
java·开发语言
FreeCode2 小时前
LangGraph1.0智能体开发:Graph API概念与设计
python·langchain·agent
test管家3 小时前
如何在Python中使用SQLite数据库进行增删改查操作?
python