小数点转化

package com.bean.utils.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Arrays;

/***
 *@title NumZeroUtil
 *@description 小数点转化
 *@author 
 *@version 1.0.0
 *@create 2025/4/7
 **/
public class NumZeroUtil {

    public static void main(String[] args) {
        testPointToZero();
        testZeroToPoint();
    }

    private static void testPointToZero() {
        String dataLength = "17,2";
        String length = "17";
        String cheineseStr = "-1009063523.93";
        cheineseStr = numToformatZero(dataLength, length, new BigDecimal(cheineseStr));
        System.out.println(cheineseStr);
    }

    private static void testZeroToPoint() {
        String item = "-0011972";
        String dataLength = "8,6";
        item = formatZeroToNum(dataLength, item);
        System.out.println(item);
    }

    /**
     * 0转小数点
     * @param dataLength
     * @param formatZero
     * @return
     */
    private static String formatZeroToNum(String dataLength, String formatZero) {
        String[] typeArr = dataLength.split(",");
        long math = (long) Math.pow(10, Integer.parseInt(typeArr[1]));
        BigDecimal num = new BigDecimal(formatZero);
        return num.divide(new BigDecimal(math)).toString();
    }

    /**
     * 小数点转0
     * @param dataLength
     * @param length
     * @param num
     * @return
     */
    private static String numToformatZero(String dataLength, String length, BigDecimal num) {
        String[] typeArr = dataLength.split(",");
        // 创建数组,默认补0
        int integerLength;
        if (num.signum() < 0) {
            integerLength = Integer.parseInt(length);
        } else {
            integerLength = Integer.parseInt(length) + 1;
        }

        int decimalLength = typeArr.length > 1 ? Integer.parseInt(typeArr[1]) : 0;
        char[] zeroChar = new char[integerLength];
        Arrays.fill(zeroChar, '0');
        // 插入小数点
        zeroChar[integerLength - decimalLength - 1] = '.';
        String paseZero = new String(zeroChar);
        DecimalFormat format = new DecimalFormat(paseZero);
        return format.format(num).replace(".", "");
    }
}
最近项目中遇到需要对字符串进行小数点转化的操作,特此记录下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值