mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-05-09 23:51:34 +08:00
NumberUtil类添加percent方法✒️
This commit is contained in:
parent
788537d9f0
commit
32e29438d7
@ -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
|
||||
|
||||
/**
|
||||
|
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user