bigdecimal and number of decimal [duplicate] - java

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);

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

BigDecimal and rounding [duplicate]

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

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));

multiply Bigdecimal and int generating error [duplicate]

This question already has answers here:
How to multiply a BigDecimal by an integer in Java
(3 answers)
Closed 8 years ago.
I have one value like 0.0004 when I store this in Integer it is converting into Exponential format, So I have used Bigdecimal to convert it to normal value like below
Bigdecimal x=BigDecimal.valueOf(0.0004)
Now I am trying to multiply as x*100 but I am getting below error.
Error: The operator * is undefined for the argument type(s) BigDecimal, int
Because of this error if I use this without bigdecimal again it is converting to EXponential.
Can any one please suggest me the way to multiply Bigdecimal and int.
googled a lot but couldn't find the correct solution.
Thanks for your time
You can use BigDecimal.multiply to multiply your BigDecimal.
However, the int value of 0.0004 * 100 will be 0, which is probably not what you want.
Finally, you can alter the how the BigDecimal is represented in terms of fractional digits by using a NumberFormat instance and formatting your Number.
Here's an example:
BigDecimal x= BigDecimal.valueOf(0.0004);
BigDecimal y = x.multiply(new BigDecimal("100"));
int z = y.intValue();
System.out.printf("y is %s\tz is %d%n", y, z);
// edit to truncate fractional digits
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.printf("y (2 fraction digits) is %s", nf.format(y));
Output
y is 0.04000 z is 0
y (2 fraction digits) is 0.04
BigDecimal's are objects. They don't have normal operators.
Instead of a normal multiplication operator like x*10, you need to call the method multiply in BigDecimal:
x = x.multiply(new BigDecimal(10));
If you want to store it in a new value:
BigDecimal n = x.multiply(new BigDecimal(10));
And to convert that to a primative:
double d = n.doubleValue();
int i = n.intValue();
However, if you're trying to use decimals, why not just use a double:
double x = 0.0004;
double n = x*100;

Java round decimal numbers [duplicate]

This question already has answers here:
round up to 2 decimal places in java? [duplicate]
(12 answers)
Closed 8 years ago.
I am trying to get a discount of an amount given
lets say: amount = "1.2" and discountPercentage = "17.3"
Code:
orig = Double.parseDouble("amount");
discount = orig*(discountPercentage/100);
discount = Math.round(discount);
discountedprice = orig - discount;
On the code above: when I round the discount using Math.round(0.2076) i am getting Zero(0) result.
What I want to happen is like this:
0.2076 = should get 0.21 when rounded up
Try this:
...
discount *= 100;
discount = Math.round(discount);
discount /= 100;
...
Error:
orig = Double.parseDouble("amount");
does not use the variable, but is a string with the content a-m-o-u-n-t.
String amount = "1.2";
double orig = Double.parseDouble(amount);
double discount = orig*(discountPercentage/100);
discount = Math.round(discount);
However be warned, that a double value can only be an approximation of a decimal number, as it is a sum of powers of 2; 0.2 being 2-3 ... Hence 100 * 0.01 is not precisely equal to 1.0.
For financial software it is better to use BigDecimal, which however is more circumstantial though. For a taste:
BigBecimal amount = new BigDecimal("1.20"); // Precision of 2 decimals.
BigDecimal discount = amount.multiply(discountPercentage.movePointLeft(2));
your code will throw a NumberFormatException because of
orig = Double.parseDouble("amount");
You are trying to parse a number from the acutal String "amount".
If you already have the amount variable initalized, you should use that variable (remove the quotes in the parseDouble method.
E.g.
String amount = "7.0";
System.out.println(Double.parseDouble(amount));
Also the types of your variables are not clear: discount, discountPercentage, discountedPrice.
Based on the code you provided in your question, a lot is not clear and therefore could be part of your problem.
Don't use Float or Double for money calculations. Use BigDecimal instead as e.g. stated here or here.
Some code:
final BigDecimal orig = new BigDecimal(1.2);
final BigDecimal discountPercentage = new BigDecimal(0.173);
final BigDecimal discount = orig.multiply(discountPercentage);
System.out.println("discount = " + discount.setScale(2, BigDecimal.ROUND_HALF_UP));
Prints:
discount = 0.21
float round(float f,float prec)
{
return (float) (Math.floor(f*(1.0f/prec) + 0.5)/(1.0f/prec));
}
use
round(0.2076f,0.01f)
result
0.21

Categories