NumberUtil类添加percent方法✒️

This commit is contained in:
大火yzs 2021-05-04 15:00:49 +08:00
parent 788537d9f0
commit 32e29438d7
2 changed files with 35 additions and 0 deletions

View File

@ -765,6 +765,18 @@ public class NumberUtil {
return (int) Math.ceil((double) v1 / v2);
}
/**
* 求百分比(取整) (3,10) => 30
*
* @param num 当前num
* @param total 总长度
* @return int 百分比(取整)
* @since 5.6.5
*/
public static int percent(int num, int total) {
return (int) ((float) num / (float) total * 100);
}
// ------------------------------------------------------------------------------------------- round
/**
@ -1082,6 +1094,19 @@ public class NumberUtil {
return format.format(number);
}
/**
* 求百分比(带精度)(带百分号后缀) (3,10,0) => 30%
*
* @param num 当前num
* @param total 总长度
* @param scale 精度(保留小数点后几位)
* @return String 百分比(带百分号后缀)
* @since 5.6.5
*/
public static String formatPercent(Number num, Number total, int scale) {
return formatPercent(num.doubleValue() / total.doubleValue(), scale);
}
// ------------------------------------------------------------------------------------------- isXXX
/**

View File

@ -178,10 +178,20 @@ public class NumberUtilTest {
Assert.assertTrue(NumberUtil.equals(new BigDecimal("0.00"), BigDecimal.ZERO));
}
@Test
public void percentTest(){
Assert.assertEquals(30, NumberUtil.percent(3, 10));
Assert.assertEquals(20, NumberUtil.percent(1, 5));
}
@Test
public void formatPercentTest() {
String str = NumberUtil.formatPercent(0.33543545, 2);
Assert.assertEquals("33.54%", str);
Assert.assertEquals("30%", NumberUtil.formatPercent(3, 10, 0));
Assert.assertEquals("33.33%", NumberUtil.formatPercent(1, 3, 2));
Assert.assertEquals("33.333%", NumberUtil.formatPercent(1, 3, 3));
}
@Test