==========================================数字格式化工具
import java.math.BigDecimal; public class DecimalFormatUtil { public static int ROUND_HALF_UP = BigDecimal.ROUND_HALF_UP;//四舍五入,舍弃部分如果大于等于5就进位,小于5的直接舍弃 public static int ROUND_HALF_DOWN = BigDecimal.ROUND_HALF_DOWN;//五舍六入,舍弃部分如果大于5才进位,小于或等于5直接舍弃 public static int ROUND_HALF_EVEN = BigDecimal.ROUND_HALF_EVEN; public static int ROUND_UP = BigDecimal.ROUND_UP;//舍弃部分如果大于等于1,就进位,否则舍弃 public static int ROUND_DOWN = BigDecimal.ROUND_DOWN;//直接截取,不进位 public static int ROUND_FLOOR = BigDecimal.ROUND_FLOOR; public static int ROUND_CEILING = BigDecimal.ROUND_CEILING; public static int ROUND_UNNECESSARY = BigDecimal.ROUND_UNNECESSARY; /** * 整数格式化(最后一位四舍五入) * @param input * @param roundingMode * @return */ public static String longFormat(BigDecimal input) { return longFormat(input, ROUND_HALF_UP); } /** * 整数格式化 * @param input * @param roundingMode * @return */ public static String longFormat(BigDecimal input, int roundingMode) { BigDecimal outputDeci = input.setScale(0, roundingMode); return outputDeci.toString(); } /** * 数字格式化(保留2位小数,最后一位四舍五入) * @param inputDouble * @return */ public static String format(BigDecimal input){ return format(input, 2, ROUND_HALF_UP); } /** * 数字格式化 * @param input * @param scale * @param roundingMode * @return */ public static String format(BigDecimal input, int scale, int roundingMode){ BigDecimal outputDeci = input.setScale(scale, roundingMode); return outputDeci.toString(); } /** * 百分数转换(两位小数,最后一位四舍五入) * @param inputStr * @return */ public static String formatPercent(BigDecimal input){ return formatPercent(input, 2, ROUND_HALF_UP); } /** * 百分数转换 * @param input * @param scale 小数位 * @param round 进位方式 * @return */ public static String formatPercent(BigDecimal input, int scale, int roundingMode){ BigDecimal inputPerent = input.multiply(new BigDecimal(100)); BigDecimal outputPerent = inputPerent.setScale(scale, roundingMode); return new StringBuffer(outputPerent.toString()).append("%").toString(); } }
==========================================数字格式化工具测试类
/** * 整数格式化 */ @Test public void test_longFormat() { BigDecimal input = new BigDecimal("2.645"); String format1 = DecimalFormatUtil.longFormat(input, DecimalFormatUtil.ROUND_HALF_UP); System.out.println(format1); String format2 = DecimalFormatUtil.longFormat(input); System.out.println(format2); } /** * 数字格式化 */ @Test public void test_format() { BigDecimal input = new BigDecimal("2.345"); String format1 = DecimalFormatUtil.format(input, 2, DecimalFormatUtil.ROUND_HALF_UP); System.out.println(format1); String format2 = DecimalFormatUtil.format(input); System.out.println(format2); } /** * 百分数转换 */ @Test public void test_formatPercent(){ BigDecimal input = new BigDecimal("2.3"); String formatPercent1 = DecimalFormatUtil.formatPercent(input, 2, DecimalFormatUtil.ROUND_HALF_UP); System.out.println(formatPercent1); String formatPercent2 = DecimalFormatUtil.formatPercent(input); System.out.println(formatPercent2); }