Converting Double to 2 Decimal Places [duplicate] - java

This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 6 years ago.
I have a code where an individual orders a certain number of coffees and coffee shots in each cup, and the program calculates the total price (purchasePrice). However, when i output the purchase price as a double, it only outputs a number with 1 decimal place. How can i change it to output with 2 decimal places.
double purchasePrice = 0;
for (counting = 0; counting < coffeeCups; counting++) {
System.out.println("Cup " + (counting + 1) + " has " + coffeeShots[counting] + " shot(s) and will cost $" + (2 + coffeeShots[counting]) + "\n");
purchasePrice+= 2 + (coffeeShots[counting]);
}
System.out.println(coffeeCups + " coffees to purchase.");
System.out.println("\nPurchase price is $" + purchasePrice + ".");

Please refer to Decimal Format
// 2 places of decimal
DecimalFormat formatter = new DecimalFormat( "#.00" );
System.out.println(formatter.format(1.23)); // 1.23
System.out.println(formatter.format(1)); // 1.00
System.out.println(formatter.format(1.234)); // 1.23

Related

Print statement [duplicate]

This question already has answers here:
How do I concatenate two strings in Java?
(23 answers)
Closed 8 months ago.
New to Java.
Does anyone know how I can print the following output:
The sum of the digits is 3 + 0 + 4 + 5 + 8 = 20
This is my print line:
System.out.print("The sum of the digits is: " + num1 + num2 + num3 + num4 + num5 + sum);
I want to get the + sign to display, but for some reason I get errors.
Any assistance is appreciated.
There is a difference between + and "+". The first is used to combine Strings in this case and the second is a String with the value of a plus sign.
So a simple plus in a String would look like this:
num1 + " + " + num2 + " = " + solution

Adding Fractions (Java) [duplicate]

This question already has answers here:
How to convert decimal to fractions?
(10 answers)
Closed 3 years ago.
In this program, the user is asked for 4 integers that represent two fractions.
First ask for the numerator of the first and then the denominator.
Then ask for the numerator and denominator of the second.
The program should add the two fractions and print out
the result.
I can't figure out how to add the fractions together
public class AddFractions extends ConsoleProgram
{
public void run()
{
int nffraction = readInt("What is the numerator of the first fraction?: ");
int dffraction = readInt("What is the denominator of the first fraction?: ");
int nsfraction = readInt("What is the numerator of the second fraction?: ");
int dsfraction = readInt("What is the denominator of the second fraction?: ");
int sum =
System.out.print(nffraction + "/" + dffraction + " + " + nsfraction + "/" + dsfraction + "=" + sum);
}
}
This is the expected output "1/2 + 2/5 = 9/10" but i can't figure out the "= 9/10" part.
To get the sum of two franctions a/b + c/d you need to do (a*d + c*b)/b*d.
So for your example:
int numerator = (nffraction * dsfraction + nsfraction * dffraction)
int denominator = dsfraction * dsfraction
System.out.print(nffraction + "/" + dffraction + " + " +
nsfraction + "/" + dsfraction + "=" + numerator + "/" + denominator);
This wont reduce to the simplest form of the fraction though.

0.05 Result Shows 4 Pennys Instead of 1 Nickel [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
This is a problem that wants me to read a double value and determine the fewest number of bills and coin needed to represent the amount.
I'm getting a weird result. I put 5.05 as the moneytotal, and I'm getting 4 pennies when it should be 1 nickel.
I think its a rounding issue but I can't see how to change it when it the problem states to use double.
Scanner scan=new Scanner(System.in);
double moneytotal, ten, five, one, quarters, dimes, nickels, pennies;
System.out.println("Input number!");
moneytotal=scan.nextDouble();
ten= moneytotal % 10;
System.out.println((moneytotal -ten)/10 + " Ten Dollar
Bills.");
five=ten% 5;
System.out.println(((ten - five)/5) + " Five Dollar Bills.");
one = five % 1;
System.out.println((five - one) + " One Dollar Bills.");
quarters = one % 0.25;
System.out.println(((one - quarters)*4) + " Quarters.");
dimes= quarters % 0.10;
System.out.println(((quarters - dimes)*10) + " Dimes.");
nickels=dimes % 0.05;
System.out.println(((dimes - nickels)*20) + " Nickels.");
pennies=nickels % 0.01;
System.out.println(((nickels - pennies) * 100)+ " Pennies.");
Actual result:
input > 5.05
5 Ten Dollar bills.
0 5 Dollar bills.
0 1 dollar bills.
0 quarters.
0 dimes.
0 nickels.
4 pennies.
Calc it as int not double because you can meet the problem regarding of the type changed.
In your code, monytotal % 10 is not 0.5 because 10 is int and % is not good for double. I think the result would be different by language.
Anyway, There is more perfect way as following:
int moneytotaln = moneytotal * 100
ten= moneytotaln % 1000;
System.out.println((moneytotaln -ten)/1000 + " Ten Dollar
Bills.");
// ...

Splitting units base of a number and separating remainders

I am trying to split a number of a base then separating the two numbers to get different outputs. (Keep in mind I just edited, my answer is the solution). This is left here so people that have a similar problem can find a solution. Thank you all!
So this is the idea:
If number >= 10 && of base 10
Then give me discounted price on 10 units
if number <= 0 && not base 10
Then add the discount for the number which has 10 units in it and the remainder without the discount (let's say 100% for simplicity sake of the numbers)
So to make a practical example
If I order 25 units of x (at $1 each) and 15 units (at $1 each) of y the price will be:
x 20 units = $0
x 5 units = $5 total
y 10 units = $0
y 5 units = $5 total
This is a bit tricky and this is what I got so far:
double discountedmNI = (mNI - ((mNI/100)*10)) * mNIC;
double discountedmNIP = mNI - ((mNI/100)*10);
if(mNIC >= 10 && mNIC % 10 == 0){
System.out.println("mNI " + discountedmNIP + " " + mNIC);
System.out.println(discountedmNI);
}
else if (!mNIC % 10 == 0){
System.out.println("mNI " + mNI + mNIC);
System.out.println(mNI * mNIC);
}
I don't think I am defining separate the 10 units right
Thank you all!
I hope I understood you right. I get that you want to calculate a total price that consists of two elements: the price for non-discounted items and a price for discounted items.
// The following three values are just example assumptions.
float discountInPercent = 100.0f;
float itemsOrdered = 5004.0f;
float itemPriceNormal = 5.0f;
// Here the price for one discounted item gets calculated.
// Please remember that the discount is given in percentage.
float itemPriceDiscounted = itemPriceNormal * ((100.0f - discountInPercent) / 100.0f);
// Calculate the count of items that get discounted and those that
// will get priced normally.
float itemsDiscounted = Math.floor(itemsOrdered / 10.0f);
float itemsNotDiscounted = itemsOrdered % 10;
// Finally calculate the two elements of the total price and sum it up.
float priceDiscounted = (itemsDiscounted * itemPriceDiscounted);
float priceNormal = (itemsNotDiscounted * itemPriceNormal);
float totalPrice = priceDiscounted + priceNormal;
System.out.println("Price discounted: %.2f" + priceDiscounted);
System.out.println("Price non-discounted: %.2f" + priceNormal);
System.out.println("Price total: %.2f" + totalPrice);
EUREKA!
double discountedmNIP = mNI - ((mNI/100)*10);
int mNIC2 = (mNIC % 10);
double mNIC2disc = (mNI * mNIC2);
double discountedmNI = (mNI - ((mNI/100)*10)) * (mNIC - mNIC2);
if(mNIC >= 10){
System.out.println(discountedmNIP + " " + (mNIC - mNIC2) + " " + discountedmNI );
System.out.println(mNI + " " + mNIC2 + " " + mNIC2disc);
}
else{
System.out.print(mNI + " " + mNIC);
System.out.print(mNI * mNIC);
}
double sum = (mNI + discountedmNI + discountedRh + rH);
System.out.println('\t');
System.out.println("Total order cost " + sum);
All I need to do is to take the units % 10 which will divide the left side integer or double by the right side (left side input from user)
and will give me the remainder when I do that variable subtracted to the original variable!
Again, this small step took me a whole night to figure it out, and is simple indeed. This is for a class, and if you are in that class and you are reading (even though you might have to dig a little to find what assignment is this one), I would just like to tell you this is what's fun about programming! I am not being sarcastic I really love these type of problems!
Signed:
That foreign guy;
EUREKA again!
Enjoy!

Average incorrect : decimal point always .0 [duplicate]

This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 5 years ago.
I'm pretty new to arrays and am trying to create a simple program that calculates the average of 5 numbers. However, when the average is calculated, it always has a decimal point of 0 rather than what it should be, but I'm not sure why..
For example, if I type in 4, 4, 4, 4, 3, it displays 3.0 as the average rather than 3.8. Please help!
int[] boxes = new int[5];
for (int i = 1 ; i <= 5 ; i++)
{
System.out.print("Enter number " + i + " > ");
int n = Integer.parseInt(kb.nextLine());
boxes[i-1] = n;
}
double mean = ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5;
System.out.println("The average of those five numbers is: " + mean);
Thank you!! :)
it is because the operation is done with integers , change your 5 to 5.0
I cannot answer you the specifics but there is a huge topic in java called type casting. I reckon, you read it. This is a good puzzle for you to solve yourself. Reminds me of my past :)
Fast fix: change 5 -> 5.0D.
Why? Let's look at dividing process more detail:
You get sum from all numbers: ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ), result -> int.
You divide sum(int type) / 5(int type) = result also int type 3.8 -> 3.
Last one its autocast int -> double.
That's why you get what you see.
Solution 1 :
- You can use 5.0 instead of 5 to have a double division.like that:
double mean = ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5.0;
Solution 2 :
- You can use a double cast of your sum like that:
double mean = (double)( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5;
To improve your answer:
You can use int n=kb.nextInt(); instead of int n = Integer.parseInt(kb.nextLine());
You can count the sum in for loop like that:
int[] boxes = new int[5];
int sum=0;
for (int i = 1 ; i <= 5 ; i++)
{
System.out.print("Enter number " + i + " > ");
int n=kb.nextInt();
boxes[i-1] = n;
sum +=boxes[i-1];
}
double mean = sum / 5.0;
System.out.println("The average of those five numbers is: " + mean);

Categories