mirror of
https://gitee.com/dromara/hutool.git
synced 2026-02-09 09:16:26 +08:00
NumberUtil.parseNumber增加支持科学计数法(pr#4211@Github)
This commit is contained in:
@@ -21,6 +21,7 @@ import cn.hutool.v7.core.convert.ConvertUtil;
|
||||
import cn.hutool.v7.core.text.CharUtil;
|
||||
import cn.hutool.v7.core.text.StrUtil;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
@@ -40,7 +41,7 @@ import java.util.Locale;
|
||||
*
|
||||
* <p>
|
||||
* 构造时可选是否将NaN转为0,默认为true。<br>
|
||||
* 参考:https://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in-java
|
||||
* 参考:<a href="https://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in-java">why-does-casting-double-nan-to-int-not-throw-an-exception-in-java</a>
|
||||
* </p>
|
||||
*
|
||||
* @author Looly
|
||||
@@ -374,6 +375,16 @@ public class NumberParser {
|
||||
// issue@4197@Github 转为半角
|
||||
numberStr = ConvertUtil.toDBC(numberStr);
|
||||
|
||||
// issue#IDJ1NS@Gitee 处理科学计数法E+格式
|
||||
// NumberFormat对E+格式支持不佳,使用BigDecimal直接解析
|
||||
if (StrUtil.containsIgnoreCase(numberStr, "e")) {
|
||||
try {
|
||||
return new BigDecimal(numberStr);
|
||||
} catch (final NumberFormatException e) {
|
||||
// BigDecimal解析失败,继续使用NumberFormat尝试
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
final NumberFormat format = NumberFormat.getInstance(locale);
|
||||
if (format instanceof DecimalFormat) {
|
||||
|
||||
@@ -528,6 +528,16 @@ public class NumberUtilTest {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void issueIDJ1NSTest(){
|
||||
final String numberstr1 = "8.37095942E+9";
|
||||
final BigDecimal result1 = (BigDecimal) NumberUtil.parseNumber(numberstr1);
|
||||
final String numberstr2 = "8.37095942e+9";
|
||||
final BigDecimal result2 = (BigDecimal) NumberUtil.parseNumber(numberstr2);
|
||||
assertEquals(new BigDecimal("8370959420").toPlainString(), result1.toPlainString());
|
||||
assertEquals(new BigDecimal("8370959420").toPlainString(), result2.toPlainString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseHexNumberTest() {
|
||||
// 千位分隔符去掉
|
||||
|
||||
Reference in New Issue
Block a user