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(".", ""); } } 最近项目中遇到需要对字符串进行小数点转化的操作,特此记录下。