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);
    }

}
相关推荐
戴誉杰9 分钟前
JAVA 程序员cursor 和idea 结合编程
java·ide·intellij-idea·cursor
板鸭〈小号〉35 分钟前
线程安全的单例模式,STL和智能指针
开发语言·c++·单例模式
小伟的技术日记39 分钟前
MATLAB下载教程MATLAB R2025a 保姆级安装步骤(附安装包)
开发语言·其他·数学建模·matlab
阿狗哲哲43 分钟前
Java选手如何看待Golang
java·开发语言·golang
测试开发技术1 小时前
软件测试中,pytest 运行完成后,如何自动发送邮件?
开发语言·python·pytest·接口测试·面试题
曹牧1 小时前
C#:dnSpy
开发语言·c#
测试19982 小时前
Pytest中实现自动生成测试用例脚本代码
自动化测试·软件测试·python·测试工具·测试用例·pytest·接口测试
唐叔在学习2 小时前
Python NumPy入门指南:数据处理科学计算的瑞士军刀
python·数据分析·numpy·数组操作·python数据处理
xzkyd outpaper2 小时前
Kotlin 协程线程切换机制详解
android·开发语言·kotlin