Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization with string in scientific format in Java BigInteger?

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.

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.

like image 934
Roman Avatar asked Jun 25 '15 12:06

Roman


People also ask

How do you write scientific notation in Java?

The format of scientific notation in Java is exactly the same as you have learned and used in science and math classes. Remember that an uppercase 'E' or lowercase 'e' can be used to represent "10 to the power of". Scientific notation can be printed as output on the console if it passes a certain number.

What is the difference between long and BigInteger?

BigInteger Larger Than Long. The signed long has a minimum value of -263 (1000 0000 … 0000) and a maximum value of 263-1 (0111 1111 … 1111). To create a number over those limits, we need to use the BigInteger class.


1 Answers

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.

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:

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

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

System.out.println(new BigDecimal(i2).toEngineeringString());
like image 172
Sergey Kalinichenko Avatar answered Sep 30 '22 16:09

Sergey Kalinichenko