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());
}
Related
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));
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));
required output:
Code: 123 Title: BookA Fees(SGD): $20.00
Loan Duration: 3 wks
return String.format("%-20s%-20s%\n", "Code: " + code, "Title: " + title, "%.2f\nFees(SGD): $" + fees, "Lesson Duration: " + lessonDuration + "wks");
it only returns only the first 3 (code, title, fees) but not loan duration. also where do i put in %.2f for fees so that it will always be of 2 decimal place?
Your question asks about "Loan Duration", but your example code uses "Lesson Duration". That could be your problem.
That %.2f should work for setting two decimal places. How is it behaving?
When you use String.format, you usually just pass your variables in and use the correct percent signs for your variables' types. For instance, if you want to format an integer, you use %d: String.format("Here is an integer: %d", myInt). For strings, you use %s, and for doubles, you use %f (with .2 to indicate the number of decimal places as you've already found out. You put all of your formatting in the first string parameter. All you have to do then is this:
String code = "123";
String title = "BookA";
double fees = 20.943;
int lessonDuration = 3;
String str = String.format("Code: %s\nTitle: %s\nFees(SGD): $%.2f\nLesson Duration: %d wks",
code,
title,
fees,
lessonDuration);
You should go read this article here so you understand formatting in Java and don't fail your test.
I want to convert Float into String, but I've got a problem with precision
I want to see something like 5.50 in String format.
If I use
String price = new DecimalFormat("#.##").format(ClientOrder.TOTAL_PRICE);
totalPriceTV.setText("" + price + " " + OptionsApp.CURRENCY);
I will get price looking like an integer, or like 5.5
ClientOrder.TOTAL_PRICE is a float number
So how to get String with 2 numbers after point?
You can write something like this too:
String price = String.format("%.2f", ClientOrder.TOTAL_PRICE);
The right pattern is "#.00".
String price = new DecimalFormat("#.00").format(ClientOrder.TOTAL_PRICE);
totalPriceTV.setText("" + price + " " + OptionsApp.CURRENCY);
You can use String.substring(int, int) with String.indexOf(String).
String totalPrice = "5.50158941";
String price = totalPrice.substring(0, totalPrice.indexOf(".") + 3);
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