This commit is contained in:
Looly 2021-09-09 19:15:43 +08:00
parent 47f1d967ed
commit a1ee4d27c3
3 changed files with 32 additions and 7 deletions

View File

@ -2154,18 +2154,28 @@ public class NumberUtil {
* 数字转{@link BigDecimal}<br>
* null或""或空白符转换为0
*
* @param number 数字字符串
* @param numberStr 数字字符串
* @return {@link BigDecimal}
* @since 4.0.9
*/
public static BigDecimal toBigDecimal(String number) {
public static BigDecimal toBigDecimal(String numberStr) {
if(StrUtil.isBlank(numberStr)){
return BigDecimal.ZERO;
}
try {
number = parseNumber(number).toString();
// 支持类似于 1,234.55 格式的数字
final Number number = parseNumber(numberStr);
if(number instanceof BigDecimal){
return (BigDecimal) number;
} else {
return new BigDecimal(number.toString());
}
} catch (Exception ignore) {
// 忽略解析错误
}
return StrUtil.isBlank(number) ? BigDecimal.ZERO : new
BigDecimal(number);
return new BigDecimal(numberStr);
}
/**
@ -2500,7 +2510,13 @@ public class NumberUtil {
*/
public static Number parseNumber(String numberStr) throws NumberFormatException {
try {
return NumberFormat.getInstance().parse(numberStr);
final NumberFormat format = NumberFormat.getInstance();
if(format instanceof DecimalFormat){
// issue#1818@Github
// 当字符串数字超出double的长度时会导致截断此处使用BigDecimal接收
((DecimalFormat) format).setParseBigDecimal(true);
}
return format.parse(numberStr);
} catch (ParseException e) {
final NumberFormatException nfe = new NumberFormatException(e.getMessage());
nfe.initCause(e);

View File

@ -13,6 +13,7 @@ import org.junit.Assert;
import org.junit.Test;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
@ -334,4 +335,12 @@ public class ConvertTest {
Assert.assertEquals("v2", hashtable.get("a2"));
Assert.assertEquals("v3", hashtable.get("a3"));
}
@Test
public void toBigDecimalTest(){
// https://github.com/dromara/hutool/issues/1818
String str = "33020000210909112800000124";
final BigDecimal bigDecimal = Convert.toBigDecimal(str);
Assert.assertEquals(str, bigDecimal.toPlainString());
}
}

View File

@ -283,7 +283,7 @@ public class NumberUtilTest {
Assert.assertEquals(1482, v1);
Number v2 = NumberUtil.parseNumber("1,482.00D");
Assert.assertEquals(1482L, v2);
Assert.assertEquals(1482L, v2.longValue());
}
@Test