I'm new to java and I've hit a sort of 'syntax learning curve' here. I was wondering how I would get the Doubles in my program i.e. "rate", to format to "#.00"?
I assume I'd have to use "DecimalFormat" to do this but I'm not quite sure how to go about using it to achieve what I want in this situation:
StringTokenizer st = new StringTokenizer(reader.readLine());
while (st.hasMoreTokens())
{
DecimalFormat df = new DecimalFormat("#.00");
hours = Integer.parseInt(st.nextToken()); // Converts number of hours to double
rate = Double.parseDouble(st.nextToken()); // Converts rate to integer
totalCost += (hours * rate);
System.out.println("Rate = £" + rate + "\t" + "Hours = " + hours);
}
Unfortunately I'm still at the stage where the Oracle Documentation is 95% incomprehensible to me so any helpful insights here would be most welcome :)
EDIT: printout currently looks like this...
Rate = £8.0
Should look like this:
Rate = £8.00
I think this should work:
System.out.println("Rate = E" + df.format(rate) + "\t" + "Hours = " + hours);
You defined the DecimalFormat, but never used it in the printing.
Display it like this:
System.out.println("Rate = £" + df.format(rate) + "\t" + "Hours = " + hours);
Related
Im having trouble to find a way for formatting this:
System.out.println("Product price reported as $" + price + " before tax and $" + result + " after " + this.tax + " % tax"):
Im trying like this.
String formatDecimals = String.format("%.2f","Product price reported as $" + price + " before tax and $" + result + " after " + this.tax + " % tax"):
I want to have two decimals. Any help
You are trying to format a string as a float, this will not work. The whole text has to go into the "format" parameter:
String formatDecimals = String.format("Product price reported as $%.2f before tax and $%.2f after %.2f %% tax", price, result, this.tax);
The project I am working on requires a bank account balance to be printed using a toString method. I am not allowed to add any methods to my current program, but I need to format my myBalance variable to a double that goes to two decimal places instead of one. In this particular instance my program should be printing 8.03, but it is printing 8.0.
Here is my toString method:
public String toString()
{
return"SavingsAccount[owner: " + myName +
", balance: " + myBalance +
", interest rate: " + myInterestRate +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
I am very new to Java still, so I would like to know if there is a way to implement %.2f into the string somewhere to format only the myBalance variable. Thank you!
Use String.format(...) for this:
#Override
public String toString() {
return "SavingsAccount[owner: " + myName +
", balance: " + String.format("%.2f", myBalance) +
", interest rate: " + String.format("%.2f", myInterestRate) +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
or more succinctly:
#Override
public String toString() {
String result = String.format("[owner: %s, balance: %.2f, interest rate: %.2f%n" +
"number of withdrawals this month: %d, service charges for this month: %.2f, " +
"myStatusIsActive: %s]",
myName, myBalance, myInterestRate, myMonthlyWithdrawCount,
myMonthlyServiceCharges, myStatusIsActive);
return result;
}
Note that khelwood asked about my use of "%n" for a new-line token rather than the usual "\n" String. I use %n because this will allow the java.util.Formatter to get a platform specific new-line, useful in particular if I want to write the String to a file. Note that String.format(...) as well as System.out.printf(...) and similar methods use java.util.Formatter in the background so this applies to them as well.
Use String.format()
Example :
Double value = 8.030989;
System.out.println(String.format("%.2f", value));
Output :
8.03
This question already has answers here:
How do I round a double to two decimal places in Java? [duplicate]
(21 answers)
Closed 8 years ago.
final double YearDep= 0.15; //this is for each year a car loses of the value before
double HybridDepreciation= HybridCarCost * Math.pow(1-YearDep,5);
double HybridFuelCost=(Miles*5*GasCost)/HybridCarMPG;
double GasPowerDepreciation=GasPowerCost * Math.pow(1-YearDep,5);
double GasPowerFuelCost=(Miles *5*GasCost)/GasPowerMPG;
double HybridTotalCost=HybridCarCost - HybridDepreciation + HybridFuelCost;
double GasPowerTotalCost= GasPowerCost - GasPowerDepreciation + GasPowerFuelCost;
System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ HybridTotalCost);
System.out.println();
System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+ GasPowerTotalCost);
use DecimalFormat for this:
DecimalFormat df = new DecimalFormat(".00");
System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ df.format(HybridTotalCost));
System.out.println();
System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+ df.format(GasPowerTotalCost));
Or you can use
String.format("The total cost for the %s is $%.2f", HybridName ,HybridTotalCost)
DecimalFormat df = new DecimalFormat("#.00");
then
df.format(<your_value>);
Or
System.out.println( String.format( "%.2f", <your_value> ) );
You can use.
double roundOff1 = (double) Math.round(HybridTotalCost);
double roundOff2 = (double) Math.round(GasPowerTotalCost);
and you can also use.
DecimalFormat df = new DecimalFormat("###.##");
System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ df.format(HybridTotalCost));
System.out.println();
System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+df.format(GasPowerTotalCost));
double roundOff = Math.round(a*100)/100.0;
or
DecimalFormat number = new DecimalFormat("#.00");
number.format(new Double(2223.8990))
I'm coding a simulation of a sports game, and it works fine for the most part; compiles and runs like it should. The directions ask that I I assume that I am supposed to be using printf and %.2f, but whenever I try to incorporate that into my code, it ceases to run properly. Help would be much appreciated!
import java.util.Scanner;
public class Team {
public String name;
public String location;
public double offense;
public double defense;
public Team winner;
public Team(String name, String location) {
this.name = name;
this.location = location;
this.offense = luck();
this.defense = luck();
}
public double luck() {
return Math.random();
}
Team play(Team visitor) {
Team winner;
double home;
double away;
home = (this.offense + this.defense + 0.2) * this.luck();
away = (visitor.offense + visitor.defense) * visitor.luck();
if (home > away)
winner = this;
else if (home < away)
winner = visitor;
else
winner = this;
return winner;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter name and location for home team (on separate lines)");
String homeName = s.next();
String homeLocation = s.next();
Team homeTeam = new Team(homeName, homeLocation);
System.out.println("Enter name and location for home team (on separate lines)");
String awayName = s.next();
String awayLocation = s.next();
Team awayTeam = new Team(awayName, awayLocation);
Team winnerTeam = homeTeam.play(awayTeam);
System.out.printf("Home team is:" + homeName + " from" + homeLocation + " rated" + homeTeam.offense + " (offense) +" + homeTeam.defense + " (defense)" + "\n");
System.out.printf("Away team is:" + awayName + " from" + awayLocation + " rated" + awayTeam.offense + " (offense) +" + awayTeam.defense + " (defense)" + "\n");
System.out.printf("Winner is:" + winnerTeam.name + " from" + winnerTeam.location + " rated" + winnerTeam.offense + " (offense) +" + winnerTeam.defense + " (defense)" + "\n");
}
You have misunderstood the printf method. You do not concatenate strings the way you do in this line and its successors (reformatted for width reasons):
System.out.printf("Home team is:" + homeName +
" from" + homeLocation +
" rated" + homeTeam.offense +
" (offense) +" + homeTeam.defense +
" (defense)" + "\n");
This is like the way an old coworker tried to use PreparedStatements to prevent SQL injection attacks, but constructed the query string by concatenation anyway, making the attempt ineffective. Instead, look at the signature of printf:
public PrintWriter format(String format, Object... args)
The first argument is a format string, which contains static text and format directives beginning with %. In typical use, each format directive corresponds to one argument of the method. Replace the interpolated variables with directives.
Strings are usually formatted with %s: s for string. Doubles are usually formatted with %f: f for float (or double). Characters between the % and the letter are options. So, let's replace the strings you interpolated with directives:
"Home team is: " + "%s" + // Inserted a space.
" from" + "%s" +
" rated" + "%6.2f" + // Six characters, 2 after the decimal.
" (offense) +" + "%6.2f" +
" (defense)" + "%n" // %n means the appropriate way to get a new line
// for the encoding.
Now we put it all together:
System.out.format("Home team is: %s from %s rated %6.2f (offense) + %6.2f (defense)%n",
homeName, homeLocation, homeTeam.offense, homeTeam.defense);
This is a lot simpler. Additionally, another reason to avoid interpolating strings in a format string is that the strings you interpolate may contain a percent sign itself. See what happens if you unguardedly write this:
String salesTax = "5%";
System.out.format("The sales tax is " + salesTax);
That's equivalent to
System.out.format("The sales tax is 5%");
Unfortunately, the percent sign is treated as a format directive, and the format statement throws an exception. Correct is either:
System.out.format("The sales tax is 5%%");
or
String salesTax = "5%";
System.out.format("The sales tax is %s", salesTax);
But now I should ask why you did not take homeName and homeLocation from Team. Certainly they are more relevant to Team than to each other. In fact, you should look up the Formattable interface, and with proper coding you can write:
System.out.format("%s%, homeTeam);
Try this:
public class A {
public static void main(String[] args) {
System.out.println(String.format("%.2f", 12.34123123));
}
}
I am very new to Java and playing with displaying a message with GUI. So if use the console
System.out.printf("Your total montly bill is $%.2f", totalCost);
gives me the output with decimal the way it should. I am trying to do the same thing with this, but I get more digits after the decimal because totalCost is a type double. How can I format the output to only show two digits after the decimal? Thanks.
JOptionPane.showMessageDialog(null, "Your monthly payment is " + totalCost);
You could do:
JOptionPane.showMessageDialog(null, String.format("Your monthly payment is $%.2f", totalCost));
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
JOptionPane.showMessageDialog(null, "Your monthly payment is " + df.format(d));
System.out.println(df.format(d));
Class DecimalFormat API
You can also do:
JOptionPane.showMessageDialog(this, "Your monthly payment is " + totalCost);
DecimalFormat df = new DecimalFormat("#.##");
String hour = JOptionPane.showInputDialog("Please input your hourly salary: ");
double hr = Double.parseDouble(hour);
double dr = hr * 8;
double wr = hr * 40;
double mr = hr * 160;
double yr = mr * 12;
JOptionPane.showMessageDialog(null, "Yearly: " + df.format(yr) + " / " + "Monthly: "
+ df.format(mr) + " / " + "Weekly: "+ df.format(wr) + " / " + "Hour: " + df.format(hr),
"Yearly Salary Calculator by the hour", JOptionPane.OK_OPTION, icon);