how-to

Math

How to compute with better precision (BigInteger/BigDecimal)

With classes java.math.BigInteger, java.math.BigDecimal you can compute with better precision. Enabled are bit operations too.

/* -- using of BigInteger */
    
BigInteger bi1 = BigInteger.valueOf( 5 );
BigInteger bi2 = BigInteger.valueOf( 7 );
    
BigInteger br = bi1.add( bi2 );
System.out.println( br.doubleValue() );
    
/* -- using of BigInteger - working with bites */
    
BigInteger bi1_1 = BigInteger.valueOf( 0 );        
bi1_1 = bi1_1.setBit( 0 );
bi1_1 = bi1_1.setBit( 2 );
System.out.println( bi1_1.intValue() );
    
/* -- using of BigDecimal */
    
BigDecimal bd1 = BigDecimal.valueOf( 10 );
BigDecimal bd2 = BigDecimal.valueOf( 2 );    
BigDecimal bdr = bd1.divide( bd2 );
System.out.println( bdr.doubleValue() );

The output will be:

12.0
5
5.0