BigDecimal and rounding [duplicate] - java

This question already has answers here:
Rounding Bigdecimal values with 2 Decimal Places
(5 answers)
Closed 2 years ago.
I have been looking for answers here re: rounding and BigDecimal, but I am having trouble. Can someone help?
The actual result of the below division is 11.469...
BigDecimal a = new BigDecimal(0.32);
BigDecimal b = new BigDecimal(2.79);
BigDecimal diffPercent = (a.divide(b, 2, RoundingMode.HALF_EVEN)).multiply(HUNDRED); // 11.00
BigDecimal diffPercent = (a.divide(b, 4, RoundingMode.HALF_EVEN)).multiply(HUNDRED); // 11.4700
How can I get 11.47 (two decimal places)?

Instead of multiplying by BigDecimal(100), move the decimal point to the right:
BigDecimal diffPercent = (a.divide(b, 4, RoundingMode.HALF_EVEN)).movePointRight(2)
Output: 11.47
This works because moving the decimal point only adjusts the scale of the BigDecimal.

BigDecimal bg = new BigDecimal("11.468");
MathContext mc = new MathContext(3); // 3 precision
// bg1 is rounded using mc
final BigDecimal round = bg.round(mc, RoundingMode.CEILING);
System.out.println(round);
Posting as this is another example of how to round

Related

Big Decimal trim to two decimal places [duplicate]

This question already has an answer here:
Rounding BigDecimal to *always* have two decimal places
(1 answer)
Closed 2 years ago.
Below code gives me about 14 decimal places. How can i trim it to the 2 decimal place?
public class BigDecimalGenerator
{ public static void main(String[] args)
{ BigDecimal max = new BigDecimal("50.00");
BigDecimal min = new BigDecimal("-50.00");
BigDecimal range = max.subtract(min);
BigDecimal result = min.add(range.multiply(new BigDecimal(Math.random())));
System.out.println(result); }
}
Use this method on BigDecimal
setScale(int newScale, int roundingMode)
using the desired scale (2) and roundingmode.
Set the rounding mode and scale.
BigDecimal max = new BigDecimal("50.00");
BigDecimal min = new BigDecimal("-50.00");
BigDecimal range = max.subtract(min);
BigDecimal result = min
.add(range.multiply(new BigDecimal(Math.random())));
result = result.setScale(2,RoundingMode.HALF_UP);
System.out.println(result);
Prints something like.
-31.28

Calculate percentage with BigDecimals [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I want to calculate the of a number I receive in BigDecimal format :
BigDecimal number1 = new BigDecimal("17");
int percentage = 50;
BigDecimal percentageAmount = number1.multiply(new BigDecimal(percentage/100));
but I got a 0 !
Cast the divided result to double. The integer division is returning zero as expected. This should work.
BigDecimal percentageAmount = number1.multiply(new BigDecimal((double)percentage/100));
Or, make the 100 to 100.0.
BigDecimal percentageAmount = number1.multiply(new BigDecimal(percentage/100.0));
These solutions would work if the number is small as you have used. But these solutions won't give the precise results when the number is big. This would be the best approach for avoiding the precision error:
BigDecimal percentageAmount = number1.multiply(BigDecimal.valueOf((double)percentage/100));

BigDecimal with smart precision (scale) [duplicate]

This question already has answers here:
Removing trailing zeros from BigDecimal in Java
(6 answers)
Closed 5 years ago.
How to set generic scaling according to decimal roundness as a number
BigDecimal num = new BigDecimal(25)
BigDecimal result = num.divide(new BigDecimal(13), 7, RoundingMode.HALF_EVEN)
// 1.9230769
but
BigDecimal result = num.divide(new BigDecimal(10), 7, RoundingMode.HALF_EVEN)
// 2.5000000 that should be 2.5
Probably analyzing remainder?
Is there something in the API for such case?
Look At https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#stripTrailingZeros--
BigDecimal bd = new BigDecimal("235.000");
System.out.println( bd.stripTrailingZeros() );

bigdecimal and number of decimal [duplicate]

This question already has answers here:
Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part
(5 answers)
Closed 6 years ago.
I try to do some caculation to get tax value. That work but it's display to much number.
Price it's a BigDecimal
BigDecimal tps = price().multiply(tpsRate());
tps.setScale(2, BigDecimal.ROUND_UP);
BigDecimal tvq = price().multiply(tvqRate());
tvq.setScale(2, BigDecimal.ROUND_UP);
BigDecimal tps = report.getPrice().multiply(report.getTpsRate());
tps.setScale(2, BigDecimal.ROUND_UP);
BigDecimal tvq = report.getPrice().multiply(report.getTvqRate());
tvq.setScale(2, BigDecimal.ROUND_UP);
If the price is 200.00
tvq it's calculated to 14.0000
tps it's calculated to 18.0000
price().add(tvq).add(tps)
total 232.0000
I want to get 14.00, 18.00 and 232.00
BigDecimal, like String, are immutable. This means you can't change the value, only return a new value.
tvq.setScale(2, BigDecimal.ROUND_UP);
This calculates a BigDecimal with two decimal places, but you are discarding it. I suspect you wanted to keep the value returned.
tvq = tvq.setScale(2, BigDecimal.ROUND_UP);

How to roundup a Double value up to two precision [duplicate]

This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
I have a Double value Double val = 49.569632
How can I roundup the val to get 49.57
You can use the DecimalFormat.
double d = 4.569632;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Or you can use the below method as mentioned in this answer as Luiggi Mendoza suggested.
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
A simple way to round is when printing
double val = 49.569632; // this should be a primitive, not an object
System.out.printf("%.2f%n", val);
or you can round the value first
double rounded = Math.round(val * 1e2) / 1e2;
System.out.println(rounded);
IMHO Using BigDecimal is slower, more complicated to write and no less error prone than using double if you know what you are doing. I know many developer prefer to use a library than write code themselves. ;)

Categories