What is the difference between this two call? (Is there any?)
// 1.
new BigDecimal("3.53456").round(new MathContext(4, RoundingMode.HALF_UP));
// 2.
new BigDecimal("3.53456").setScale(4, RoundingMode.HALF_UP);
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead.
Here's my note about that on my blog:
http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html
Related
Consider the following BigDecimals
BigDecimal("6.0000").precision() // = 5
BigDecimal("0.20000").precision() // = 5
When you divide those BigDecimals:
BigDecimal("6.0000").divide(BigDecimal("0.20000")) // = 3E+1
And
BigDecimal("6.0000").divide(BigDecimal("0.20000")).precision() // = 1
So dividing two BigDecimals with a precision of 5 results in BigDecimal with a precision of 1. Even when explicitly setting the precision to 5 by providing a MathContext, the result is the same:
BigDecimal("6.0000").divide(BigDecimal("0.20000"), MathContext(5, RoundingMode.HALF_UP)) // = 3E+1
When I set the scale on the other hand, I end up with a higher precision
BigDecimal("6.0000").divide(BigDecimal("0.20000"), 5, RoundingMode.HALF_UP).precision() // = 7
Is there a way to keep the precision when performing a division as above? Is this only possible by specifying a scale instead of a precision?
Regarding the scale, the javadoc states that the preferred scale for divisions is dividend.scale() - divisor.scale(). However, it also states that
These scales are the ones used by the methods which return exact arithmetic results; except that an exact divide may have to use a larger scale since the exact result may have more digits. For example, 1/32 is 0.03125.
Isn't that the case in the above situation, as the exact results requires more digits?
In your case, it does not really matter, because the result is precise. If you need concrete precision (maybe for parsing), use setScale on the end.
If a function would need to lose precision to give you a result (for instance, because of dividing 1 by 3), dividing would throw an exception (in case of using the divide function, because Kotlin div operator would round the result, losing precision). That is why it is better to set precision and rounding mode by yourself when you divide.
import java.math.BigDecimal
import java.math.RoundingMode.HALF_EVEN
fun main() {
val a = BigDecimal("1.0")
val b = BigDecimal("3.0")
val c = a.divide(b, 10, HALF_EVEN)
println(c) // 0.3333333333
println(c.precision()) // 10
}
I'm a little bit confused because I lose precision all the time.
Maybe I'm operating with the wrong type. I have a String like "100.00". But when I do
Double.parseDouble("100.00") it is being cut off to 100. Need help. Thanks in advance.
You probably printed your number with System.out.println(d). It will internally call Double.toString(double), whose specification states
How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double.
This is because the double number has no notion of "decimal precision". It is a binary number with fixed binary precision (number of binary digits after the binary point).
Just use BigDecimal instead of Double like this:
BigDecimal houndred = new BigDecimal("100.00").setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal does not loose precision at all. Additionally you can set scale, precision and rounding mode as you prefer.
I've stumbled across interisting thing(maybe only for me) in scala. In a word, if we have a BigDecimal(let say val a = BigDecimal(someValue) where someValue is decimal string) the result of operation
N * a / N == a
will not always produce true. I suppose that it relates to any opeartions on BigDecimals. I know that in scala BigDecimals are created with default MathContext set to DECIMAL128(with HALF_EVEN rounding and precision equals to 34). I've discovered such behavior on decimals with more than 30 digits after point
My questions is why I get such results. Can I somehow control them?
example
-0.007633587786259541984732824427480916
As previous comments already point out, this is not avoidable with irrational numbers. This is because there's no way to represent an irrational number using the standard numeric types (if at all). Since I have no examples with irrational numbers (even PI is limited to a fixed number of digits, and therefore can be expressed as a quotient of 2 whole numbers, making it rational), I will use repeating decimals to illustrate the problem. I changed N*a/N to a/N*N because it demonstrates the problem better with whole numbers, but they're equivalent:
a = BigDecimal(1)
N = BigDecimal(3)
a/N = 0.333...
a/N*N = 0.999...
As you can see in the example above, you can use as many decimal places and any rounding mode, but the result is never going to be equal to 1. (Though it IS possible to get 1 using a different rounding mode per operation, i.e. BigDecimal(3, roundHalfEven) * (BigDecimal(1, roundUp) / 3))
One thing you can do to control the number comparison is to use a higher precision when performing your arithmetic operations and round to the desired (lower) precision when comparing:
val HighPrecision = new java.math.MathContext(36, java.math.RoundingMode.HALF_EVEN);
val TargetPrecision = java.math.MathContext.DECIMAL128;
val a = BigDecimal(1, HighPrecision)
val N = BigDecimal(3, HighPrecision)
(a/N*N).round(TargetPrecision) == a.round(TargetPrecision)
In the example above, the last expression evaluates to true.
UPDATE
To answer your comment, although BigDecimal is arbitrary precision, it is still limited by a precision. It can be 34 or it can be 1000000 (if you have enough memory). BigDecimal does NOT know that 1 / 3 is 0.33<repeating>. If you think about how division works, there's no way for BigDecimal to conclusively know that it's repeating without performing the division to infinite decimal places. But since a precision of 2 indicates it can stop dividing after 2 decimal places, it only knows that 1 / 3 is 0.33.
BigDecimal numerator = new BigDecimal(numerator);
BigDecimal denominator = new BigDecimal(denominator);
double result = numerator.divide(denominator).doubleValue();
Division on certain conditions results in a zero at the end (e.g. 0.0060).
Dividing equal numbers results in a zero at the end (e.g 1.0).
I would prefer to trim the trailing zero in both cases. How should I do this?
How about keeping the result as a BigDecimal and then you can set the scale on it to only represent the significant figures that you want.
An easy way to do this, for some numbers, is to use BigDecimal#stripTrailingZeros(). However, if the number is an integer with trailing zeros you'll get an engineering representation e.g. 600.0 will give you 6E+2. If this isn't what you want, you'll have to detect this condition and manually use BigDecimal#setScale() to set the scale appropriately.
If you need to keep to a restricted maximum number of decimal digits you'll need to use alternative formatting/rounding mechanisms before applying this technique.
It's also a good idea to only do this on values that you're going to display, not on the internal values of your model. Treat it as a view/presentation layer modification.
If you must convert to a double, then it's only the formatted representation you can alter. In this case, if you've got a variable number of decimal places that you want to format to, I'd just drop it into a string/character array, scan backwards for the first non-zero character and truncate it there. Not the most performant means, but simple and reliable.
You could even use a regex for this purpose.
you can do this by using DecimalFormat. something like:
DecimalFormat df = new DecimalFormat(".0");
double formatResult = df.format(result);
will create something of 1.0 if the result is 1.278494890. there are many possible patterns that could be used here
Ok, so you've got this code:
BigDecimal numerator = new BigDecimal(numerator);
BigDecimal denominator = new BigDecimal(denominator);
double result = numerator.divide(denominator).doubleValue();
and you want more control over your output. Since result is a double, which is a primitive, you won't have much control.
From my understanding, you don't want to do any rounding to n decimal places, you want original precision paired with desired formatting.
You have few options.
BigDecimal numerator = new BigDecimal(numerator);
BigDecimal denominator = new BigDecimal(denominator);
BigDecimal div = numerator.divide(denominator);
If you stay with BigDecimal, your output will be better. If you put 10 as the numerator and denominator in above code, System.out.println(div) will yield 1.
Generally, be careful of using above code because some combinations of numerator and denominator will throw
java.lang.ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result."
If you want to avoid such situations, and not worry about precision beyond double's internal representation, use double directly.
System.out.println(2312 / 2.543); //909.1624066063704
System.out.println(1.0 / 1.0); //1.0
System.out.println(1 / 1); //1
When using double numbers, you might get a 0 at the end, such as 0.0060 in your case. If you want to be sure what you're getting, you'll have to convert your result to a String using
String dec = String.valueOf(10.0/10.0); //1.0
and then using
String newDec = dec.endsWith("0") ? dec.substring(0, dec.length() - 1) : dec;
to eradicate that last 0. Of course, if your string ends with .0, you have a choice based on your preferences whether you want to leave that leading . or not.
Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal. If yes why does not it round the decimal digits but even mantissa part.
From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online.
Please let me know if you have any idea on this.
For rounding just the fractional part of a BigDecimal, check out the BigDecimal.setScale(int newScale, int roundingMode) method.
E.g. to change a number with three digits after the decimal point to one with two digits, and rounding up:
BigDecimal original = new BigDecimal("1.235");
BigDecimal scaled = original.setScale(2, BigDecimal.ROUND_HALF_UP);
The result of this is a BigDecimal with the value 1.24 (because of the rounding up rule)
#jatan
Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method.
There's nothing special about BigDecimal.round() vs. any other BigDecimal method. In all cases, the MathContext specifies the number of significant digits and the rounding technique. Basically, there are two parts of every MathContext. There's a precision, and there's also a RoundingMode.
The precision again specifies the number of significant digits. So if you specify 123 as a number, and ask for 2 significant digits, you're going to get 120. It might be clearer if you think in terms of scientific notation.
123 would be 1.23e2 in scientific notation. If you only keep 2 significant digits, then you get 1.2e2, or 120. By reducing the number of significant digits, we reduce the precision with which we can specify a number.
The RoundingMode part specifies how we should handle the loss of precision. To reuse the example, if you use 123 as the number, and ask for 2 significant digits, you've reduced your precision. With a RoundingMode of HALF_UP (the default mode), 123 will become 120. With a RoundingMode of CEILING, you'll get 130.
For example:
System.out.println(new BigDecimal("123.4",
new MathContext(4,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.CEILING)));
System.out.println(new BigDecimal("123.4",
new MathContext(1,RoundingMode.CEILING)));
Outputs:
123.4
1.2E+2
1.3E+2
2E+2
You can see that both the precision and the rounding mode affect the output.
I would add here, a few examples. I haven't found them in previous answers, but I find them useful for those who maybe mislead significant digits with number of decimal places. Let's assume, we have such context:
MathContext MATH_CTX = new MathContext(3, RoundingMode.HALF_UP);
For this code:
BigDecimal d1 = new BigDecimal(1234.4, MATH_CTX);
System.out.println(d1);
it's perfectly clear, that your result is 1.23E+3 as guys said above. First significant digits are 123...
But what in this case:
BigDecimal d2 = new BigDecimal(0.000000454770054, MATH_CTX);
System.out.println(d2);
your number will not be rounded to 3 places after comma - for someone it can be not intuitive and worth to emphasize. Instead it will be rounded to the first 3 significant digits, which in this case are "4 5 4". So above code results in 4.55E-7 and not in 0.000 as someone could expect.
Similar examples:
BigDecimal d3 = new BigDecimal(0.001000045477, MATH_CTX);
System.out.println(d3); // 0.00100
BigDecimal d4 = new BigDecimal(0.200000477, MATH_CTX);
System.out.println(d4); // 0.200
BigDecimal d5 = new BigDecimal(0.000000004, MATH_CTX);
System.out.println(d5); //4.00E-9
I hope this obvious, but relevant example would be helpful...
If I'm understanding you correctly, it sounds like you're expecting the MathContext to control how many digits should be kept after the decimal point. That's not what it's for. It specifies how many digits to keep, total. So if you specify that you want 3 significant digits, that's all you're going to get.
For example, this:
System.out.println(new BigDecimal("1234567890.123456789",
new MathContext(20)));
System.out.println(new BigDecimal("1234567890.123456789",
new MathContext(10)));
System.out.println(new BigDecimal("1234567890.123456789",
new MathContext(5)));
will output:
1234567890.123456789
1234567890
1.2346E+9
It's not for fun. Actually I found some online example, which stated the use of MathContext to round the amounts/numbers stored in BigDecimal.
For example,
If MathContext is configured to have precision = 2 and rounding mode = ROUND_HALF_EVEN
BigDecimal Number = 0.5294, is rounded to 0.53
So I thought it is a newer technique and used it for rounding purpose. However it turned into nightmare because it started rounding even mentissa part of number.
For example,
Number = 1.5294 is rounded to 1.5
Number = 10.5294 is rounded to 10
Number = 101.5294 is rounded to 100
.... and so on
So this is not the behavior I expected for rounding (as precision = 2).
It seems to be having some logic because from patter I can say that it takes first two digits (as precision is 2) of number and then appends 0's till the no. of digits become same as unrounded amount (checkout the example of 101.5294 ...)