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

}
相关推荐
紫金修道1 分钟前
【DeepAgent】概述
开发语言·数据库·python
Via_Neo3 分钟前
JAVA中以2为底的对数表示方式
java·开发语言
书到用时方恨少!9 分钟前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
cch891813 分钟前
PHP五大后台框架横向对比
开发语言·php
Warson_L39 分钟前
Python 常用内置标准库
python
天真萌泪1 小时前
JS逆向自用
开发语言·javascript·ecmascript
Warson_L1 小时前
Python 函数的艺术 (Functions)
python
Warson_L1 小时前
Python 流程控制与逻辑
后端·python
野生技术架构师1 小时前
一线大厂Java面试八股文全栈通关手册(含源码级详解)
java·开发语言·面试
long_songs1 小时前
手柄键盘映射器【github链接见文末 】
python·游戏·计算机外设·pygame·软件推荐·手柄映射键盘