数据存储单位转换,b、byte、KB、MB、GB、TB转换工具类

该博客介绍了一个用于存储单位换算的Java工具类,包括字节、KB、MB、GB和TB之间的转换。提供了静态常量定义存储单位,并且包含一个方法convert用于根据指定的小数点位数进行转换。博客中通过示例展示了如何使用该工具类将1500KB转换为MB以及将1500b转换为byte。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.sv.admin.commons.utils;

import java.math.BigDecimal;

/**
 * 存储单位换算
 *
 * @author Gltqe
 * @date 2022/7/3 0:31
 **/
public class StorageUnitUtil {

    public static final Long BIT = 1L;
    public static final Long BYTE = 8L;
    public static final Long KB = 8 * 1024L;
    public static final Long MB = 8 * 1024 * 1024L;
    public static final Long GB = 8 * 1024 * 1024 * 1024L;
    public static final Long TB = 8 * 1024 * 1024 * 1024L * 1024L;
    public static final Integer SCALE = 2;

    /**
     * 存储单位换算
     *
     * @param length      需要转换的存储大小
     * @param currentUnit 当前存储单位
     * @param targetUnit  转换目标存储单位
     * @param scale       小数点
     * @return java.math.BigDecimal
     * @author Gltqe
     * @date 2022/7/3 0:32
     **/
    public static BigDecimal convert(BigDecimal length, Long currentUnit, Long targetUnit, Integer scale) {
        if (scale == null) {
            scale = SCALE;
        }
        if (currentUnit < targetUnit) {
            BigDecimal b1 = new BigDecimal(targetUnit / currentUnit);
            BigDecimal decimal = length.divide(b1, scale, BigDecimal.ROUND_HALF_UP);
            return decimal;
        } else if (currentUnit > targetUnit) {
            BigDecimal b1 = new BigDecimal(currentUnit / targetUnit);
            BigDecimal decimal = length.multiply(b1).setScale(scale, BigDecimal.ROUND_HALF_UP);
            return decimal;
        } else {
            return length;
        }
    }

    public static void main(String[] args) {
        // 测试 : 1500KB 转为 MB // 结果: 1.465
        BigDecimal convert1 = convert(new BigDecimal("1500"), KB, MB, 3);
        System.out.println(convert1);
        // 测试 : 1500b 转为 byte // 结果: 187.500
        BigDecimal convert2 = convert(new BigDecimal("1500"), BIT,BYTE, 3);
        System.out.println(convert2);
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值