How to implement Math.round to achieve 3dp output? - java

public class Favorite {
public static void main(String[] arguments) {
String itemName = "Golden Beans";
double offerPrice = 314;
int sellPrice = 321;
double value = (sellPrice - offerPrice);
int cashStack = 500_000;
double percentageProfit = ((value / offerPrice) * 100);
System.out.println("Approx. Offer Price is " + offerPrice);
System.out.println("Approx. Sell Price is " + sellPrice);
System.out.println("The potential profit margin is " + value);
System.out.println("With a cash stack of " + cashStack + " we can buy " + cashStack / offerPrice + " " + itemName +"s");
System.out.println("The profit margin of " + itemName + " as a percentage is " + percentageProfit);
}
}
make a mini program that I determine buy and sell price for and it tells me the profit margin. DONE
then find out how many of the item I can purchase for 500,000. DONE
then make it more advanced by getting the program to tell me what the profit is of the buy price. DONE
then have the program output to 3 decimal places. (This is where I'm stuck!)

Read the documentation first - java docs:
System.out.printf("%.3f", res);
or DecimalFormat
System.out.println(new java.text.DecimalFormat("#.000").format(500.12321313));

Try printf() instead of println() use format %.3f:
System.out.printf("The profit margin of %s as a percentage is %.3f%n" itemName,percentageProfit);

You seem to be looking for DecimalFormat
https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
That class is able to do a lot of work with formatting numbers, from changing the separators to automatically round up the numbers the way you desire.
Try to instantiate one of these, then configure it, and play a bit with the options until you understand how it works, and finally just call its "format" method on whatever number you want to transform to a String.

Related

find the difference between a negative and positive number

I have a value stored in my db.table as arrears which has a minus sign eg arrears = -100.0 and when an amount is to be paid to cancel or reduce the arrears, am getting wrong results. eg:
arrears = -100.0 is displayed in a jtextfiled named 'arrears' from db.table
user inputs amount to be paid into a textbox named 'pay'.
a calculation must be done and new arrears must be entered back into 'arrears' jtextfield.This is the code I wrote below:
double a,b,e;
a=Double.valueOf(arrears.getText());
b=Double.valueOf(pay.getText());
e=a+b;
arrears.setText(String.valueOf(e));
arreas= -100.0, amount paid = 50.0 after the calculation I get answer as -45.0 instead of -50. please what is the problem.
It is look like problem isn't in a calculation. I recommend you using debugger or logging, for example:
double a,b,e;
System.out.println("arrears = " + arrears.getText());
System.out.println("pay =" + pay.getText());
a=Double.valueOf(arrears.getText());
b=Double.valueOf(pay.getText());
e=a+b;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("e = " + e);
arrears.setText(String.valueOf(e));
User enters 5 in pay text field—> 5 is added to arrears, user enters 0 into pay text field —> 50 is added and total value is now -100 + 5 + 50 = 45

How do I use "BigDecimal" in Java for my specific code?

I'm very new to programming in Java. I have been given an assignment in my school to solve the following exercise:
"Create two variables, each containing a number. Put out a message that shows how often the second number fits into the first one, and the rest (if there is one)" [I hope the wording is clear. I'm translating this from my native language german into english]
Now in general, I have solved the exercise like this (using Netbeans):
double numberOne = 10, numberTwo = 35.55;
double result, rest;
String conversion, numberOutput;
result = numberTwo / numberOne;
conversion = Double.toString(result);
int indexOfComma = conversion.indexOf(".");
numberOutput = conversion.substring(0, indexOfComma);
rest = numberTwo % numberOne;
System.out.println("The second number fits " + numberOutput +
" times into the first one. The rest is: " + rest);
With the numbers provided, the system pops out this message:
"The second number fits 3 times into the first one. The rest is: 5.549999999999997"
I don't like the rounding error for the rest. I expected it to give out "5.55" like a human would type or write it. After a bit of googling around it seems that something called "BigDecimal" is the solution to my problem, but the explanations I found of how to implement this in Java go wayyy over my head.
Would you be so kind as to show me exactly where and how I need to use BigDecimal in the above code to get the desired output? I would also be happy to see any alternative solutions you can think of.
BigDecimal version of your code:
BigDecimal numberOne = new BigDecimal("10");
BigDecimal numberTwo = new BigDecimal("35.55");
BigDecimal[] divRem = numberTwo.divideAndRemainder(numberOne);
System.out.println("The second number fits " + divRem[0].stripTrailingZeros().toPlainString() +
" times into the first one. The rest is: " + divRem[1].stripTrailingZeros().toPlainString());
Output
The second number fits 3 times into the first one. The rest is: 5.55
You can use BigDecimal like
BigDecimal a = BigDecimal.valueOf(10);
BigDecimal b = BigDecimal.valueOf(35.55);
BigDecimal c = b.divide(a, 3, BigDecimal.HALF_UP);
System.out.println(b + " / " + a + " = " + c);
Or you could use rounding like
System.out.printf("(int)(%.2f / %d) = %d%n", 35.55, 10, (int) (35.55 / 10));
System.out.printf("%.2f %% %d = %.2f%n", 35.55, 10, 35.55 % 10);
which prints
floor(35.55 / 10) = 3
35.55 % 10 = 5.55

Java Error: first type: double, second type: String

I just started learning Java programming, and received this error on my first project in the last part, "fee before taxes" I must be messing up my variables, but I am not sure. Any ideas?
This is the error I receieved on the compiler:
error: bad operand types for binary operator
first type: double
second type: String
2 errors
import java.util.Scanner;
public class project1Naja {
public static void main(String[] args) {
String firstName; // To hold first name
String lastName; // To hold last name
String hours; // Child's hours
final String date; // Date of Service
final double RATE; // Hourly rate
final double TAX_RATE; // Tax percentage
int fee; // Cost before tax added
int taxAmount; // Tax total
double totalFee; // Fee including tax
// Scanner created to read input.
Scanner childCare = new Scanner(System.in);
System.out.print("Enter your first name: " );
firstName = childCare.nextLine();
System.out.print("Enter your last name: " );
lastName = childCare.nextLine();
System.out.print("Enter the child's hours here: " );
hours = childCare.nextLine();
System.out.print("Enter date here: " );
date = childCare.next();
System.out.println("Child Care Service Bill For: " + firstName
+ lastName);
System.out.println("Date of Service: " + date);
System.out.println("Number of hours: " + hours);
System.out.println("Fee before taxes: " = RATE * hours);
}
}
You need to initialize local variables before accessing them,
in this case RATE is local variable which is uninitialized at the time it is being accessed
System.out.println("Fee before taxes: " = RATE * hours);
initialize it by
final double RATE = 0.50; // some rate value
and also String cannot be multiplied with double
2 things to note here..
String hours;
hours is string so you cannot multiply any variable with a string
System.out.println("Fee before taxes: " = RATE * hours);
wrong syntax... it should be System.out.println("Fee before taxes: =" + RATE * hours);
also RATE and whatever you multiply with it plz initialize both.
Your code doesn't compile because Firstly the = out of " " is for assignement, so the first thing to do is to keep it inside the "Fee before taxes: ".
Second, you can't use the Multiplication Operator * between String and a double, in order to do that you need to parse the String like that: Double.parseDouble(hours).
Third, you need to initialize all local variables (final or not) before using them as they don't have default values in Java, you can learn mor about local variables from the Java docs.
It's also detailed in the Definite Assignment:
For every access of a local variable or blank final field x, x must be
definitely assigned before the access, or a compile-time error occurs.
So, for your example, the only variable used before assignement is RATE, so you don't have to initialize the others:
final double RATE = 0; // for example
At the end, your code must look something like this:
import java.util.Scanner;
public class project1Naja {
public class project1Naja {
public static void main(String[] args) {
String firstName; // To hold first name
String lastName; // To hold last name
String hours; // Child's hours
final String date; // Date of Service
final double RATE = 0; // Hourly rate
final double TAX_RATE = 0; // Tax percentage
int fee; // Cost before tax added
int taxAmount; // Tax total
double totalFee; // Fee including tax
// Scanner created to read input.
Scanner childCare = new Scanner(System.in);
System.out.print("Enter your first name: ");
firstName = childCare.nextLine();
System.out.print("Enter your last name: ");
lastName = childCare.nextLine();
System.out.print("Enter the child's hours here: ");
hours = childCare.nextLine();
System.out.print("Enter date here: ");
date = childCare.next();
System.out.println("Child Care Service Bill For: " + firstName
+ lastName);
System.out.println("Date of Service: " + date);
System.out.println("Number of hours: " + hours);
System.out.println("Fee before taxes: " + RATE
* Double.parseDouble(hours));
}
}
There are three things here that make it so your code cannot correctly compile.
You defined hours as a String. This would be ok if you were only looking to display the string without manipulating it or combining it with another string. However, this line:
System.out.println("Fee before taxes: " = RATE * hours);
is trying to tell the compiler to multiply a type String with a type double. You cannot do this in java. Hours will have to be defined as either a double to match your RATE, or as a byte, int, short, long or float. Keep in mind that if you want partial hours (such as .5 hours) you will need to use either double or float, since these are the only two primitive data types that can be manipulated with decimals without adding a cast type.
Alternatively, you can parse the String as a double with something that looks like Double.parseDouble(hours), but this is an indirect "work-around" way of dealing with the issue, so I recommend changing the type of hours instead.
Whenever you declare a final of any data type in java, you must assign it a value as well. You cannot simply leave it undefined as you have in your list of variables. It should say something along the lines of
final double RATE = 7.2;
Because of this when you try the line:
System.out.println("Fee before taxes: " = RATE * hours);
the compiler calls the final which has not yet been declared, and therefor a compilation error occurs. Variables on the other hand, can remain uninitiated but they must be assigned a value that matches their data type before they are actually referenced in lines of code. If they are not you will get a compilation error.
In your final print statement you have ("Fee before taxes" = RATE * hours).
This is a simple syntax error. You can never have the operand = in a print statement. The only operand allowed (for this basic case's sake) is + to add more text to the string. This line should read:
System.out.println("Fee before taxes" + (RATE * hours));
IN SHORT :
Change your variable hours to type double, assign your final RATE to a number, and change the syntax error in your final print statement. After that you should have smooth sailing.
P.S.
I also noticed you have two more finals called "date" and "TAX_RATE". These should be declared as well, otherwise you will come across similar errors when implementing them.
Hope this helps!

Why is it adding the variables wrong?

I'm using Java but, it's not adding the amount correctly. I'll give my parts of my code.
final double taxrate=.08;
Map<String,Integer> Priceproduct= new HashMap<String,Integer>();
Priceproduct.put("shoes",(int) 50.00);
Priceproduct.put("shirts",(int) 30.00);
Priceproduct.put("shorts",(int) 75.00);
Priceproduct.put("caps",(int) 15.00);
Priceproduct.put("jackets",(int) 100.00);
System.out.print("\n Enter the product: ");
String product=keyboard.nextLine();
System.out.print( "\n Enter the quantity of the product");
int quantity=keyboard.nextInt();
int cost= Priceproduct.get(product)*quantity;
int tax= (int) (cost*taxrate);
System.out.print("\n tax=" +cost*taxrate+"");
int TotalBill= cost+tax;
System.out.print("\nTotal="+cost+ + +tax+"");
When it adds the cost and tax (those two are correct) it's gets the completely wrong answer.
For example 3 shirts= 90, the tax equals 7.2, and the total becomes 907.
Do I need to use DecimalFormat or something else?
Change this:
System.out.print("\nTotal="+cost+ + +tax+"");
to this:
System.out.println();
System.out.print("Total=" + (cost + tax));
(The problem is that + is left-associative, so without parentheses around your addition, "a" + b + c means ("a" + b) + c, which does string-concatenation at both stages.)
When you perform an operation alongside a string Java will perform that operation as if the operands were strings.
In your System.out.println() calls you don't need to redo the calculations, just print out the variables "tax" and "totalBill". (This will solve the problem of printing '907')
You will only ever get integer values because you are using int type for everything. If you want to have decimals to indicate cents you should be using type double.

Return a double with only two decimals in Java as part of a larger string?

As part of a larger program, I have this function that, when called, returns the string under return. accountHolder, balance, interestRate, and points are variables in an object of type RewardsCreditAccount. So, for example, I declare an object here:
RewardsCreditAccount testAccount = new RewardsCreditAccount("Joe F. Pyne", 7384.282343837483298347, 0.173, 567);
So this object will set accountHolder = "Joe F. Pyne", balance = 7384.282343837483298347, and so on.
In the function below, I return this information in a string that should look like this:
Joe F. Pyne, $7384.282, 17.28%, 567 points
Using this function:
public String toString() {
return (accountHolder + ", $" + + balance + 100*interestRate + "%, " + points + " points");
}
However, it is in fact returning this:
Joe F. Pyne, $7384.282, 17.299999999999997%, 567 points
I tried this, but to no avail
public String toString() {
return (accountHolder + ", $" + + ("%,1.2f",balance) + 100*interestRate + "%, " + points + " points");
}
This is rather annoying, because I want it to only return two decimal places. I know this can be done using %1.2f, but I have no idea how to format the syntax for that. I would vastly appreciate any help on getting the decimal value to display properly. Thanks!
You'll have to use String.format(); with that format-String.
So this
public String toString() {
return (accountHolder + ", $" + + ("%,1.2f",balance) + 100*interestRate + "%, " + points + " points");
}
Should be:
public String toString() {
return String.format("%s, $%,1.2f %s%%, %s points", accountHolder, balance, 100*interestRate, points );
}
With the formatters set so that it is printed according to your desires.
Use DecimalFormater for formatting your value.
new DecimalFormat("###.##").format(17.299999999999997);
For reference.
You will need to use String.format() to format your returned String: -
String.format("%5.2f",balance)
Floating point numbers are not always easy to deal with.
Your problem lies in the fact that floating point types (as float and double, and their boxed counterparts) are just binary approximations of their decimal representation, so all kinds of such problems can arise when not taking this into count.
You also have to pay attention when handling very large values, because it can occur that (a== (a+1))==true...
Also, for currencies, and other such critical data, I'd recommend BigDecimal, which stores the exact string representation, not the binary approximation. That is not the most trivial thin on Earth to handle though, but given the criticality of data, I think it is unavoidable.

Categories

Resources