mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
change NumberUtil.toStr
This commit is contained in:
parent
59202e8061
commit
f0399a72ad
@ -7,6 +7,7 @@
|
||||
|
||||
### 新特性
|
||||
* 【http 】 HttpRequest增加basicProxyAuth方法(issue#I1YQGM@Gitee)
|
||||
* 【core 】 NumberUtil.toStr修改逻辑,去掉BigDecimal的科学计数表示(pr#196@Gitee)
|
||||
|
||||
### Bug修复
|
||||
* 【core 】 修复ChineseDate没有忽略时分秒导致计算错误问题(issue#I1YW12@Gitee)
|
||||
|
@ -1967,20 +1967,20 @@ public class NumberUtil {
|
||||
|
||||
/**
|
||||
* 数字转字符串<br>
|
||||
* 调用{@link Number#toString()},并去除尾小数点儿后多余的0
|
||||
* 调用{@link Number#toString()}或 {@link BigDecimal#toPlainString()},并去除尾小数点儿后多余的0
|
||||
*
|
||||
* @param number A Number
|
||||
* @return A String.
|
||||
*/
|
||||
public static String toStr(Number number) {
|
||||
if (null == number) {
|
||||
throw new NullPointerException("Number is null !");
|
||||
}
|
||||
|
||||
if (false == ObjectUtil.isValidIfNumber(number)) {
|
||||
throw new IllegalArgumentException("Number is non-finite!");
|
||||
Assert.notNull(number, "Number is null !");
|
||||
|
||||
// BigDecimal单独处理,使用非科学计数法
|
||||
if(number instanceof BigDecimal){
|
||||
return toStr((BigDecimal)number);
|
||||
}
|
||||
|
||||
Assert.isTrue(isValidNumber(number), "Number is non-finite!");
|
||||
// 去掉小数点儿后多余的0
|
||||
String string = number.toString();
|
||||
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) {
|
||||
@ -1994,6 +1994,19 @@ public class NumberUtil {
|
||||
return string;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link BigDecimal}数字转字符串<br>
|
||||
* 调用{@link BigDecimal#toPlainString()},并去除尾小数点儿后多余的0
|
||||
*
|
||||
* @param bigDecimal A {@link BigDecimal}
|
||||
* @return A String.
|
||||
* @since 5.4.6
|
||||
*/
|
||||
public static String toStr(BigDecimal bigDecimal) {
|
||||
Assert.notNull(bigDecimal, "BigDecimal is null !");
|
||||
return bigDecimal.stripTrailingZeros().toPlainString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 数字转{@link BigDecimal}
|
||||
*
|
||||
|
@ -279,4 +279,12 @@ public class NumberUtilTest {
|
||||
final Set<?> set = Convert.convert(Set.class, ints);
|
||||
Assert.assertEquals(5, set.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStrTest(){
|
||||
Assert.assertEquals("1", NumberUtil.toStr(new BigDecimal("1.0000000000")));
|
||||
Assert.assertEquals("0", NumberUtil.toStr(NumberUtil.sub(new BigDecimal("9600.00000"), new BigDecimal("9600.00000"))));
|
||||
Assert.assertEquals("0", NumberUtil.toStr(NumberUtil.sub(new BigDecimal("9600.0000000000"), new BigDecimal("9600.000000"))));
|
||||
Assert.assertEquals("0", NumberUtil.toStr(new BigDecimal("9600.00000").subtract(new BigDecimal("9600.000000000"))));
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user