find the difference between a negative and positive number - java

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

Related

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

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.

Displaying BigDecimal as Integer while Keeping Original Value

The purpose of this program is to give correct change. For Example:
Input: $45.54
Output: 4 Ten Dollar Bills,
1 Five Dollar Bills,
2 Quarters,
4 Pennies.
Now onto my question:
I want to display a BigDecimal as an integer without losing the original value, as I have to continue my division all the way down until i get to 0.01 for pennies.
My Current Code looks like:
BigDecimal tenDollar = BigDecimal.valueOf(10);
BigDecimal tenDollarNext;
BigDecimal fiveDollar = BigDecimal.valueOf(5);
BigDecimal fiveDollarNext;
/* Get Input From User */
System.out.print("Please enter the amount to be converted: ");
Scanner scan = new Scanner(System.in);
BigDecimal money = scan.nextBigDecimal();
NumberFormat usdFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdFormat.setMinimumFractionDigits(2);
usdFormat.setMaximumFractionDigits(2);
System.out.println("Amount you entered: " + usdFormat.format(money));
/* Begin Processing and Displaying Information */
tenDollarNext = money.divide(tenDollar);
System.out.println(tenDollarNext + " Ten Dollar Bills");
fiveDollarNext = tenDollarNext.divide(fiveDollar, 0, RoundingMode.FLOOR);
System.out.println(fiveDollarNext + " Five Dollar Bills");
Which ends up Displaying:
Please enter the amount to be converted: 45.54
Amount you entered: $45.54
4.554 Ten Dollar Bills
0 Five Dollar Bills
My goal is to have the 4.554 be displayed as 4 without losing the decimal places at the end for the calculation. I'm sure there is a simple answer to this, I was hoping someone could either tell me the conversion for it or point me in the direction of where I could find the answer. None of my search queries have been helpful.
Use the divideToIntegralValue method of the BigDecimal class, in place of divide. This returns a BigDecimal whose value is an integer. You can then subtract the appropriate amount from money and continue on.

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

how to exchange an amount of money into notes and coins

how can I exchange a given amount of money into notes and coins? lets say input is 1234,26
and we have notes for 1000, 500, 200, 100, 50, and coins for 20, 10, 1, and 0.5? so if input is greater than .25 and less than .75 it should be rounded to 1x 0.5 if its between .75 and 1.00 it should be rounded to 1x 1 and if its less than .25 it should be rounded to nothing?¨
for this exact program the desired output would look something like this:
1x: 1000
1x: 200
1x: 20
1x: 10
4x: 1
1x: 0.5
if it wasnt for the 0.5 coin, I think I would have been able to do it using int and %, but as of right now I am pretty much clueless(think I have to use array, but im not sure how) and have no idea how to start. also im beginnner, if you can keep that in mind as well when answering and explaining! any tips/solutions? thanks in advance!
like this?:
System.out.println((input/1000) + " thousand " + ((input/500)%2) + " fivehundred " + (input/200%2.5) + " two hundred " + (input/100%2) + " hundred " + (input/50%2) + " fifty " + (input/20%2.5) + " twenty " + (input/10%2) + " ten " + input/1%10 + " one " );
still not sure how to deal with the 0.5 since I have to use int, input only cuz if I use double I get it completely wrong, I also have to use a if statement for the 0.5 coin..
I believe this is the standard approach to this kind of question.
double input = 1234.26;
int thousands = input/1000;
input = input - 1000*thousands; //So now it would 234,26
int fivehundreds = input/500;
input = input - 500*fivehundreds;
etc...
Right, but you can't convert from double to int (i.e. thousands is an int, but input is a double, so input/1000 is a double). So you have a few options:
Make thousands, fivehundreds, etc... be double. That is kinda ugly, though, there's no way they will have any decimal valu
Casting mean anything to you? For example, (int)int thousands = input/1000; will work. You can read up on "casting", but basically I'm just telling Java to treat that number as an int, not a double
Keep input as a int, and round it down. Then just check at the end if it has a decimal value (input % 1 > 0), and if it does, you need a half dollar.

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.

Categories

Resources