I received an assignment at university in Java where I have to use printf to format output to the console. It was all nice and dandy but for some reason I am getting the output 10500.000000000002, the right output should be 10500.00. I tried to use the %0.2f, but because I formatted in a String I cannot do it.
This is the line in question:
System.out.printf("\nAge Depreciation Amount:%66s","$"+ ageDepreciationAmount);
Can you please suggest a way to format this properly? Please keep in mind this is an introductory course to java, which means I am a complete disaster when it comes to programming.
DecimalFormat df = new DecimalFormat("0.##");
String result = df.format(10500.000000000002);
%0.2f is not correct. You should use %.2f:
Example:
System.out.printf("Age Depreciation Amount: %.2f\n", ageDepreciationAmount);
Or if ageDepreciationAmount is a String do
System.out.printf("Age Depreciation Amount: %.2f\n", Double.parseDouble(ageDepreciationAmount));
BTW we usually add the \n after the printf, and not before.
Output:
Age Depreciation Amount: 10500.00
If you want to fill the output with spaces, you would use %66.2, where 66 is the total width, and 2 is the number of decimal digits. However this only works for numbers. Since you need to also print the dollar sign, you can do it in two steps like this:
double ageDepreciationAmount = 10500.000000000002;
double ageDepreciationAmount2 = 100500.000000000002;
String tmp = String.format("$%.2f", ageDepreciationAmount);
String tmp2 = String.format("$%.2f", ageDepreciationAmount2);
System.out.printf("Age Depreciation Amount: %20s\n", tmp);
System.out.printf("Age Depreciation Amount: %20s\n", tmp2);
Output:
Age Depreciation Amount: $10500.00
Age Depreciation Amount: $100500.00
Related
Without changing the code, how would I be able to change the output from being 13.00 to 13:00? Is it possible to do so in the printf string?
System.out.print("Please enter the current hour on the clock(no minutes): ");
double time = sc.nextDouble();
System.out.print("Please enter the duration in hours: ");
int duration = sc.nextInt();
double newTime = (time+duration)-24;
System.out.println();
System.out.printf("If it is %.2f, in %d hours, it will be %.2f.\n",time,duration,newTime);
I would recommend replacing the "." to ":" as a stand-alone line. I don't see why you'd want to do that within the printf. Nonetheless, here is an example of how you could do it
System.out.printf("If it is %s.\n", String.valueOf(time).replace(".",":"));
Essentially converting the double to a string, then replacing the character.
Also, remember to change the %s tag.
I'm taking my java class, and I'm working on a Tsubo calculator for my assignment. I don't usually ask questions on stack overflow so forgive me if this seems basic. I've done some searching here and tried some of the solutions but none have worked in my case. I'm going to copy just part of my conversion below
```
System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");
sqftInput = keyboard.nextInt();
// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftResultAsString + " Tsubo"); `
When I do this, it tells me I can't format a double that the type is not applicable to arguments for DecimalFormat.
When I change it to look like this (offending line is commented out)
' System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");
sqftInput = keyboard.nextInt();
// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftFormatted + " Tsubo");
The program compiles and runs, and when I use 5238 as an input number, then my output looks like this --> 5238.0 is equal to :java.text.DecimalFormat#674dc Tsubo
instead of actually displaying the answer which is 325.07.
I've also tried using some regex formatting using the stringFormat but i wind up getting illegalformatting exception.
Long story short, What I'm trying to achieve is an output that is formatted to 2 decimal places, and then converted to a string that the system outputs as an answer. What am I missing? Is this Decimal Format automatically converting this to a string object?
DecimalFormat is used to produce a formatted String. If you print it directly, it will show its (kind of, it's called idenity hashcode) memory address cause that is what the DecimalFormat.toString() does.
Instead, you should use it to produce your output string and print that directly.
As follows:
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
String out = sqftFormatted.format(sqftResult); // or whatever you want to print
//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + out + " Tsubo");
See docs for more details
Whenever I compile and run my code, the output becomes a big mess and I would like if someone could show me how to make my output look good.
import java.util.*;
public class JavaApplication3 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int NumPerHamper;
int NumHampersMade;
int NumItemsLeftOver;
int NumAvalable;
double ValuePerHamper;
double ItemCost;
double ValueAllotedHamper;
double ValueItemsLeftOver;
String name="";
Date TheDate = new Date();
System.out.println("Enter the number of avaliable mac and cheese");
NumAvalable = sc.nextInt();
System.out.println("Enter the number of items per hamper");
NumPerHamper = sc.nextInt();
System.out.println("Price Of Item");
ItemCost = sc.nextDouble();
NumHampersMade = NumAvalable / NumPerHamper;
NumItemsLeftOver = NumAvalable % NumPerHamper;
ValuePerHamper = NumPerHamper * ItemCost;
ValueAllotedHamper = ValuePerHamper * NumHampersMade;
ValueItemsLeftOver = NumItemsLeftOver * ItemCost;
System.out.printf("\n");
System.out.printf(TheDate + "\n");
System.out.printf("Amount of Hampers Made: ", NumHampersMade,"\n");
System.out.printf("The Items Left Over is: ", NumItemsLeftOver,"\n");
System.out.printf("Each Value Of the Hampers are: $%.2f.", ValuePerHamper,"\n");
System.out.printf("The Price Of All The Hampers Is: $%.2f.", ValueAllotedHamper,"\n");
System.out.printf("The Value Of Mac And Cheese Is: $%.2f.", ValueItemsLeftOver,"\n");
}
}
This isn't right:
System.out.printf("Each Value Of the Hampers are: $%.2f.", ValuePerHamper,"\n");
The first argument (the format string) is the string you actually print, after replacing "format specifiers", or placeholders. Format specifiers in that string, such as %.2f, get substituted with the other arguments. So the second argument, ValuePerHamper, is used for the first specifier, %.2f; and the third argument, \n, is used for the second specifier---um, except that there aren't any other specifiers, so it doesn't get used at all.
You want to put \n in the format string:
System.out.printf("Each Value Of the Hampers are: $%.2f.\n", ValuePerHamper);
(printf also allows you to use %n instead of \n, which is more portable since it will also work on Windows systems where going to a new line needs \r\n instead of \n.)
You could use %n or \n. Either of these should be in the first parameter in the printf() method like this.
System.out.printf("Each Value Of the Hampers are: $%.2f. %n", ValuePerHamper);
System.out.printf("The Price Of All The Hampers Is: $%.2f.%n", ValueAllotedHamper);
System.out.printf("The Value Of Mac And Cheese Is: $%.2f.%n", ValueItemsLeftOver);
And you are missing %d for the first 2 lines to display the values.
System.out.printf("Amount of Hampers Made: %d %n", NumHampersMade);
System.out.printf("The Items Left Over is: %d %n", NumItemsLeftOver);
I'm a newby java guy trying to get my print out statement to format decimal placements.. I know that %.2f works, but for whatever reason when I try to apply the %.2f it bombs.... Not sure what to do.. any advice? thanks in advance!
credits = int
raise = double
System.out.printf("An undergraduate resident student taking " + credits + " currently pays $" + "%,.2f",credtotal);
System.out.println("\n");
System.out.printf("with a increase in tuition of " + (trying to format here) raise + ", per credit will become " + raisecredund + ", and an undergraduate resident taking " + credits + " credits" + " will pay $" +"%,.2f",(credits*(raise*245.73))+ credtotal);;
You appear to be using "%,.2f" with a comma which I don't think is legal. %.2f will print the number to 2 decimal places.
If you want to include a comma ever 3 places like in money you should use a DecimalFormat
DecimalFormat formatter = new DecimalFormat("#,###.00");
final String str1 = String.format("An undergraduate resident student taking %d currently pays $%.2f",credits, credtotal);
EDIT: I didn't notice that you were using printf. You were close:
System.out.printf("An undergraduate resident student taking %d currently pays $%.2f", credits,credtotal);
Using your first example string, you supply the formatting characters inline and then provide an argument for each placeholder. Assuming credtotal is a double and knowing credits is int, the above would yield (with respective values assigned)
An undergraduate resident student taking 1 currently pays $2.00
See creating formatted strings section.
Here is the code:
import java.util.Scanner;
public class MoviePrices {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
double adult = 10.50;
double child = 7.50;
System.out.println("How many adult tickets?");
int fnum = user.nextInt();
double aprice = fnum * adult;
System.out.println("The cost of your movie tickets before is ", aprice);
}
}
I am very new to coding and this is a project of mine for school. I am trying to print the variable aprice within that string but I am getting the error in the heading.
Instead of this:
System.out.println("The cost of your movie tickets before is ", aprice);
Do this:
System.out.println("The cost of your movie tickets before is " + aprice);
This is called "concatenation". Read this Java trail for more info.
Edit: You could also use formatting via PrintStream.printf. For example:
double aprice = 4.0 / 3.0;
System.out.printf("The cost of your movie tickets before is %f\n", aprice);
Prints:
The cost of your movie tickets before is 1.333333
You could even do something like this:
double aprice = 4.0 / 3.0;
System.out.printf("The cost of your movie tickets before is $%.2f\n", aprice);
This will print:
The cost of your movie tickets before is $1.33
The %.2f can be read as "format (the %) as a number (the f) with 2 decimal places (the .2)." The $ in front of the % is just for show, btw, it's not part of the format string other than saying "put a $ here". You can find the formatting specs in the Formatter javadocs.
you are looking for
System.out.println("The cost of your movie tickets before is " + aprice);
+ concatenates Strings. , separates method parameters.
Try this one
System.out.println("The cost of your movie tickets before is " + aprice);
And you can also do that:
System.out.printf("The cost of your movie tickets before is %f\n", aprice);
This will help:
System.out.println("The cost of your movie tickets before is " + aprice);
The reason is that if you put in a coma, you are sending two different parameters. If you use the line above, you add the double onto your string, and then it sends the parameters as a String rather than a String and a double.
It occurs when you use , instead of + i.e:
use this one:
System.out.println ("x value" +x);
instead of
System.out.println ("x value", +x);
I don't know if you have found the answer yet, but I understood that you should write like this:
System.out.println(MessageFormat.format("My name is = {0}, My FirstLetter Name is {1}, Myage is = {2}",Myname,myfirstl,d));