用Java BigInteger科技格式的字符串初始化?

时间:2021-11-20 16:49:21

I have a need to work with large numbers (something in range 1E100 - 1E200). However, the BigInteger class, which seems to be suitable in general, does not recognize strings in scientific format during initialization, as well as does not support the conversion to a string in the format.

我需要处理大量的数据(范围为1E100 - 1E200)。然而,BigInteger类似乎在一般情况下是合适的,它在初始化过程中不能识别科学格式的字符串,也不支持在格式中转换为字符串。

BigDecimal d = new BigDecimal("1E10"); //works
BigInteger i1 = new BigInteger("10000000000"); //works
BigInteger i2 = new BigInteger("1E10"); //throws NumberFormatException
System.out.println(d.toEngineeringString()); //works
System.out.println(i1.toEngineeringString()); //method is undefined

Is there a way around? I cannot imagine that such class was designed with assumption that users must type hundreds of zeros in input.

有办法吗?我无法想象这样的类的设计假设用户必须在输入中输入数百个0。

1 个解决方案

#1


13  

Scientific notation applies to BigIntegers only in a limited scope - i.e. when the number in front of E is has as many or fewer digits after the decimal point than the value of the exponent. In all other situations some information would be lost.

科学的表示法只适用于有限范围内的大整数——即当E前面的数字在小数点后的位数与指数的值相同或更少时。在所有其他情况下都会丢失一些信息。

Java provides a way to work around this by letting BigDecimal parse the scientific notation for you, and then converting the value to BigInteger using toBigInteger method:

Java通过让BigDecimal为您解析科学符号,然后使用toBigInteger方法将值转换为BigInteger,从而解决这个问题:

BigInteger i2 = new BigDecimal("1E10").toBigInteger();

Conversion to scientific notation can be done by constructing BigDecimal using a constructor that takes BigInteger:

转换成科学的表示法可以通过使用具有BigInteger的构造函数来实现:

System.out.println(new BigDecimal(i2).toEngineeringString());

#1


13  

Scientific notation applies to BigIntegers only in a limited scope - i.e. when the number in front of E is has as many or fewer digits after the decimal point than the value of the exponent. In all other situations some information would be lost.

科学的表示法只适用于有限范围内的大整数——即当E前面的数字在小数点后的位数与指数的值相同或更少时。在所有其他情况下都会丢失一些信息。

Java provides a way to work around this by letting BigDecimal parse the scientific notation for you, and then converting the value to BigInteger using toBigInteger method:

Java通过让BigDecimal为您解析科学符号,然后使用toBigInteger方法将值转换为BigInteger,从而解决这个问题:

BigInteger i2 = new BigDecimal("1E10").toBigInteger();

Conversion to scientific notation can be done by constructing BigDecimal using a constructor that takes BigInteger:

转换成科学的表示法可以通过使用具有BigInteger的构造函数来实现:

System.out.println(new BigDecimal(i2).toEngineeringString());