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

}
相关推荐
疯狂成瘾者几秒前
text_splitter常见方法
python·langchain
深蓝轨迹几秒前
面试常见的jdk---LTS版本新特性梳理
java·面试·jdk
数据知道16 分钟前
claw-code 源码分析:大型移植的测试哲学——如何用 unittest 门禁守住「诚实未完成」的口碑?
开发语言·python·ai·claude code·claw code
Stella Blog18 分钟前
狂神Java基础学习笔记Day01
java·笔记·学习
李白的天不白19 分钟前
java处理跨域请求
java
炸炸鱼.23 分钟前
Python 网络编程入门(简易版)
网络·python
云烟成雨TD23 分钟前
Spring AI Alibaba 1.x 系列【11】Spring AI Models 扩展:DashScope
java·人工智能·spring
技术小黑24 分钟前
TensorFlow学习系列10 | 数据增强
python·深度学习·tensorflow2
小堃学编程24 分钟前
【项目实战】基于protobuf的发布订阅式消息队列(2)—— 线程池
java·开发语言
万粉变现经纪人28 分钟前
如何解决 import aiohttp ModuleNotFoundError: No module named ‘aiohttp’
python·scrapy·beautifulsoup·aigc·pillow·pip·httpx