Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big Decimal periodic number [duplicate]

I want to calculate with the java class BigDecimal, but I get always an exception by periodic numbers. I've been looking on the internet but unfortunately found nothing. Maybe someone can help me to fix it.

Example:

System.out.println(new BigDecimal(1).divide(new BigDecimal(3)));  
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion;   no exact representable decimal result.  
    at java.math.BigDecimal.divide(Unknown Source)  
    at Berechne.rechne(Berechne.java:16)  
    at Berechne.main(Berechne.java:39)  

System.out.println(new BigDecimal(1).divide(new BigDecimal(4))); --> 0.25

like image 728
SnowN Avatar asked Mar 24 '23 05:03

SnowN


1 Answers

You are trying to divide 1 by 3, which will have recurrent numbers after decimal point. This is what the wikipedia says :

In arithmetic, repeating decimal is a way of representing a rational number. Thus, a decimal representation of a number is called a repeating decimal (or recurring decimal) if at some point it becomes periodic, that is, if there is some finite sequence of digits that is repeated indefinitely. For example, the decimal representation of 1/3 = 0.3333333… or 0.3 (spoken as "0.3 repeating", or "0.3 recurring") becomes periodic just after the decimal point, repeating the single-digit sequence "3" infinitely.

You're not specifying a precision and a rounding-mode. BigDecimal is complaining that it could use infinity decimal places, and it still wouldn't be able to give you an exact representation of the number.

Look at the documentation:

When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)

As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quo tient could have an infinitely long decimal expansion; for example, 1 divided by 3.

If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.

To circumvent this , you can use divide(BigDecimal divisor, int scale, int roundingMode)

like image 143
AllTooSir Avatar answered Apr 02 '23 02:04

AllTooSir