formatting issues with printout statement, doubles java - java

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.

Related

Why is it concatenating instead of arithmetic operation?

Scanner sal = new Scanner(System.in);
System.out.print("Enter first_salary: ");
int Salary1 = sal.nextInt();
System.out.print("Enter second_salary : ");
int Salary2 = sal.nextInt();
System.out.print("Combined Salary is " + Salary1 + Salary2);
I am trying to get user input twice, and then print the sum. Instead, the output is concatenating the numbers instead of actually adding them.
Because the + operator associates left to right. Your argument is equivalent to the explicit
(("Combined Salary is " + Salary1) + Salary2)
Since ("Combined Salary is " + Salary1) results in a string, you will concatenate strings. To group differently, adjust the order of operations with parentheses:
System.out.print("Combined Salary is " + (Salary1 + Salary2));
As to why this happens, #MadPhysicist's answer covers that.
As to how to avoid this you can either use parentheses as they said or you can use string formatting, like this:
System.out.println("Combined Salary is %d".formatted(Salary1 + Salary2));
String has had the formatted method since Java 15. If you're stuck with an older version you can use the static format method instead:
System.out.println(String.format("Combined Salary is %d", Salary1 + Salary2));

Unexpected DecimalFormat output - Java

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

The method println(double) in the type PrintStream is not applicable for the arguments (String, double)

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));

Java format modifiers doubles in string

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

double + double = String?

I have a problem the output is supposed to be double but instead it is string
I am trying to add two double values but it is giving it as a string. I am using eclipse. Currently the program is compiling and running. If anyone have a moment I would appreciate it.Cheers guys. Here is the source code.
import java.util.Scanner;
public class FutureInvestment
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter investment amount: ");
double investmentAmount = input.nextDouble();
System.out.println("Enter monthly interest rate: ");
double monthlyInterestRate = input.nextDouble();
System.out.println("Enter number of years: ");
int numberOfYears = input.nextInt();
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate), numberOfYears * 12));
System.out.println("Accumulated value is: " + futureInterestValue + investmentAmount);
}
}
You need to format your output. You can use DecimalFormat or you can try the String#format function:
System.out.println(
String.format("Accumulated value is: %.2f",
futureInterestValue + investmentAmount));
So you can get the 2 decimal output. Plus, I recommend to create a variable with your result, so you can turn your code into
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println(
String.format("Accumulated value is: %.2f", accumulatedValue);
Since you're doing it in a println, it's doing string concatenation. If you want to add the double's together, you need to group them using ().
Try
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println("Accumulated value is: " + accumulatedValue);
Try this.
You were getting String as result of concatenation, since anything concatenated to a string is converted to string. Therefore, you need to complete the value beforehand as I shown above, or you need parentheses.
I think change it to this would work:
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate / 100), numberOfYears * 12));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
you are missing some brackets, so your statement gets executed from left to right, thus appending the double to the string. You would need something like:
System.out.println("Accumulated value is: " + (futureInterestValue +
investmentAmount));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
After the first +, Java has concatenated the first string with the first double, resulting in a string. Then it does another concatenation with the second double. You need to calculate the result first before making a string out of it.
When two operators could be evaluated within a line of code, they do so with a fixed precedence. While this example has been explained by many, you might want to review all of the precedence rules.
You can try:
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
or add a variable like double accumulatedValue=futureInterestValue + investmentAmount;
and then System.out.println("Accumulated value is: " + accumulatedValue);
The problem is your number is getting way too large, and Java switches over to scientific notation when printing the value.
If your monthly interest rate is entered as 4.25 (meaning 4.25%), you have to convert that to the correct decimal representation of 0.0425 before using it in your calculations - you have to divide it by 100. If you don't, the interest rate used will be much larger than you intended; in this case 425%.
In other words, change
double monthlyInterestRate = input.nextDouble();
to
double monthlyInterestRate = input.nextDouble()/100;

Categories

Resources