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

}
相关推荐
一水几秒前
TTFT优化:一个方案的5次推倒重来
java·ai·状态模式
编程阿峰6 分钟前
Python 环境配置(二)安装jupyter、matplotlib、numpy库
开发语言·python·jupyter·numpy·matplotlib
AC赳赳老秦7 分钟前
CSDN 技术社区数据采集:OpenClaw 抓取公开技术热帖,生成领域技术热点周报
java·大数据·前端·数据库·python·php·openclaw
磁爆步兵27 分钟前
内存分区:程序运行的核心秘密
java·开发语言·jvm
金銀銅鐵38 分钟前
[Python] 一次打开多个常用的网址
python
此生决int43 分钟前
深入理解C++系列(06)——模版初阶与STL
开发语言·c++
明如正午1 小时前
【python】Python + OpenCV 实现视频关键帧提取与智能去重
python·opencv·音视频
aqi001 小时前
15天学会AI应用开发(十八)使用LangGraph实现精确记忆功能
人工智能·python·大模型·ai编程·ai应用