How to add up many BigDecimals in Java [duplicate] - java

This question already has answers here:
Addition for BigDecimal
(12 answers)
Closed 6 years ago.
I have this program in which I need to add up many BigDecimals. I have the following snippet of code
BigDecimal Average = new BigDecimal(3.0);
BigDecimal ATT = new BigDecimal(0.0);
ATT.add(A_BigDecimal);
ATT.add(B_BigDecimal);
ATT.add(C_FullBigDecimal);
System.out.println("Total Amount: " + ATT);
System.out.println("Average: " + ATT.divide(Average));
I keep getting errors everytime I try variants of this code, how do you add many BigDecimals together?
Edit: Forgot to mention that the output is zero, always zero, as if the reference variable isnt reading the add function.

BigDecimal is immutable. Once the object is created, it cannot be changed.
The add method will return the result of the calculation. You will probably want to assign that return value to something.

This is what Joe C meant in updated code:
BigDecimal Average = new BigDecimal(3.0);
BigDecimal ATT = new BigDecimal(0.0);
ATT = ATT.add(A_BigDecimal);
ATT = ATT.add(B_BigDecimal);
ATT = ATT.add(C_FullBigDecimal);
System.out.println("Total Amount: " + ATT);
System.out.println("Average: " + ATT.divide(Average));

Related

Converting String to Double for calculation cause me problem with decimal numbers, how to round it? [duplicate]

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Adding and subtracting doubles are giving strange results [duplicate]
(2 answers)
Closed 3 years ago.
I found many answer speaking about converting String to Double (with two decimals) but I'm facing a weird case. When printing the value no problem, it is right. But when I do calculations the program acts weird.
I have this code:
String str = "21.90";
I want to convert this string into a double. I tried many solution but none works properly.
double amount = Double.valueOf(str);
or
double amount = Double.parseDouble(str);
or
try {
amount = DecimalFormat.getNumberInstance().parse(str).doubleValue();
}
catch (ParseException e){
// error
}
I've tried also with rounding methods like:
double roundOff = Math.round(amount * 100.0) / 100.0;
Number is converted in "21.9" but when I do, for example:
System.out.println(number - 21.8) = 0.09999999999999787
I don't understand why it's doing this.
Thanks in advance for your help.
You are losing precision when you make calculation with double, to make calculation, it better to use BigDecimal, so instead I would go :
String str = "21.90";
BigDecimal result = new BigDecimal(str).subtract(BigDecimal.valueOf(21.8));
System.out.println(result);
=> 0.10
System.out.println is using strings and the double is converted to a string
. A double value has no precsion at all, even if your string has 2 decimals.
So you need to format the converted string:
String str = "21.90";
double amount = Double.parseDouble(str);
System.out.println("double is: " + amount);
double roundOff = Math.round(amount * 100.0) / 100.0;
System.out.println("double rounded is: " + roundOff);
The output is:
double is: 21.9
double rounded is: 21.9
result is: 0,10
Because of my Locale DE a comma is used in the output. Or use:
System.out.println("result is: " + String.format(Locale.US,"%.2f",amount - 21.8));
System.out.println("result is: " + String.format("%.2f",amount - 21.8));

What can I do against floating point notations Errors? [duplicate]

This question already has answers here:
Why are floating point numbers inaccurate?
(5 answers)
Why not use Double or Float to represent currency?
(16 answers)
Closed 5 years ago.
I need to multiply a float by 100 in order to convert from € to cents. The problem I am having is, that the value of big numbers isn't calculated correctly.
For example:
String aa = "1000009.00";
aa = aa.replaceAll(",", ".");
float bb = Float.parseFloat(aa);
bb=Math.round(bb*100);
System.out.println(bb);
What I am getting is: 1.00000896E8
So I know this is because of the way float in Java works.
I have searched for an answer but people always say "use Math.round()" which doesn't work for me.
What can i do to prevent this?
You can use double for more precision (or BigDecimal if you expect to work with very big numbers).
String aa = "1000009.00";
double bb = Double.parseDouble(aa);
bb=Math.round(bb*100);
System.out.printf("%.2f", bb); // it prints only two digits after the decimal point
Output
100000900.00
You can use BigDecimal::multiply for example :
String aa = "1000009.00";
aa = aa.replaceAll(",", ".");
BigDecimal fullValue = new BigDecimal(aa);
System.out.println("full value = " + fullValue.multiply(new BigDecimal(100)));
Output
full value = 100000900.00

Force double to display 2 decimal points [duplicate]

This question already has answers here:
Best way to Format a Double value to 2 Decimal places [duplicate]
(2 answers)
How to round a number to n decimal places in Java
(39 answers)
Closed 5 years ago.
Bit of a silly one, but just to clarify I know I can format the output to a string and then format the string in a variety of ways to achieve this but I need the return value to stay as a double as it has multiple uses.
So basically I have a LinkedList that i am reading values in from that was formatted as a double when imported. I am then using the sum of these values to essentially calculate a total which I am using in a toString function and a couple of other places.
My issue is if there are trailing zeros they are trimed so the values is as small as possible. e.g: 3.50 -> 3.5, 0.00 -> 0.0 and so on.
public double totalCost(){
double total = 0.00;
for(Ingredient cost : ingredients){
total += cost.ingredientCost();
}
return total;
The code above is the sum code.
public String toString(){
return crust() + " pizza with " + toppings() + " and " + sauce() + ": $" + totalCost();
}
And this is my toString function.
Any guidance would be awesome.
I think this will help you:
public String toString(){
return crust() + " pizza with " + toppings() + " and " + sauce() + ": $" + String.format( "%.2f", totalCost());
}

how to format string to show two decimal places [duplicate]

This question already has answers here:
Best way to Format a Double value to 2 Decimal places [duplicate]
(2 answers)
Closed 6 years ago.
I am facing a slight issue when trying to get two decimal places after pasring double to string and trying to format
pieChart.setCenterText("$" + "" + "" +String.format( "% 1$ .2f", Double.toString(dataCost),""));
can anyone help me improve the above line of code so that it can display to two decimal places? You will also notice that I am trying to leave a space between the dollar sign and the value
You can use String.format("%.2f", d) , your double will be rounded automatically
pieChart.setCenterText("$ " + String.format("%.2f", d));
Following code might help you
double a = 1.234567;
double a = 2;
NumberFormat nf = new DecimalFormat("##.##");
System.out.println(nf.format(a));
System.out.println(nf.format(a));
and the output will be
1.23
2
it only show decimal places if needed, Enjoy! :)
Try Like This
pieChart.setCenterText("$ " + String.format("%.2f", dataCost));
You can use DecimalFormat.
import java.text.DecimalFormat;
DecimalFormat money = new DecimalFormat ("$0.00");
System.out.println(money.format(dataCost));
Try this.
float val = 1245.235645f;
double ans = Double.parseDouble(new DecimalFormat("##.##").format(val));
System.out.println(ans);
Note : ##.## means 2 digits will be displayed after the .(dot)
Package : import java.text.DecimalFormat;
this should helps you.

Display as two Decimal [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert a number to 2 decimal places in Java
I need to display a decimal number up to two digits in Java.
For example:
Case1. 2.333 - 2.33
Case2. 3.4 - 3.40
I am able to do the first case. Can anybody help me how to do for the second case.
If you just want to print a double with two digits after the decimal point, use something like this:
double value = 200.3456;
System.out.printf("Value: %.2f", value);
If you want to have the result in a String instead of being printed to the console, use String.format() with the same arguments:
String result = String.format("%.2f", value);
Or use class DecimalFormat:
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
You can try
System.out.printf("%.2f %.2f%n", 2.333, 3.4);
prints
2.33 3.40

Categories