Rounding a number with printf in java? - java

i am trying to use System.out.printf to round a very large number to 2 decimal places. This is the code i am using:
System.out.printf(" %1.2f = overpayment:$" + overpayment);
I am getting this error:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%1.2f'
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
I am under the impression that %f is the format specifier and %1.2f is used for a floating point number with 2 digits after the decimal.
I am trying to round 4.4260494195128784E-4 to 4.43. Thank you
Since I am getting under a cent for my overpayment, I think i have the wrong formula to calculate it. Does anyone have an idea on how to attain overpayment of a loan? The overpayment value should be 4.43. Here is my code:
import java.util.Scanner;
public class CreditCardPayoff {
public static void main(String[] args) {
// TODO Auto-generated method stub
double principle;
double annualInterestRate;
double monthlyPayment;
double numerator;
double denominator;
double monthsToPayOff;
double monthsToPayOffCeiled;
double totalAmountPaid;
double totalInterestPaid;
double overpayment;
Scanner keyboard = new Scanner(System.in);
principle = keyboard.nextDouble();
annualInterestRate = keyboard.nextDouble();
monthlyPayment = keyboard.nextDouble();
numerator = Math.log(monthlyPayment) - Math.log(monthlyPayment-
(annualInterestRate / 1200.00) * principle);
denominator = Math.log((annualInterestRate/1200.00) + 1.0);
monthsToPayOff = numerator/denominator;
monthsToPayOffCeiled = Math.ceil(monthsToPayOff);
totalAmountPaid = monthsToPayOffCeiled * monthlyPayment;
totalInterestPaid = totalAmountPaid - principle;
overpayment = (monthsToPayOffCeiled - monthsToPayOff)/monthlyPayment;
System.out.println("Principle:" + principle);
System.out.println("Annual Interest Rate:" + annualInterestRate);
System.out.println("Monthly Payment:" + monthlyPayment);
System.out.println("Months Needed To Pay Off:" + (int)monthsToPayOffCeiled);
System.out.println("Total Amount Paid: $" + totalAmountPaid);
System.out.println("Total Interest Paid: $" + totalInterestPaid);
System.out.printf("overpayment: $%1.2f ", overpayment);
}
}
My method to calculate overpayment, obtain difference between monthsToPayOff and monthsToPayOffCeil (ceiling) then divide by monthly payment. This got me 4.4260494195128784E-4.

In order to use String.format you do not concatenate the values for the placeholders with the format string, but rather pass them as parameters:
System.out.printf("overpayment: $%1.2f", overpayment);

printf takes one argument for every format specifier (see documentation). In Java arguments are separated by commas (,).
So, in your example, instead of a + that concatenate two strings (a string and a number into a string, to be precise), you should use a comma:
System.out.printf(" %1.2f = overpayment:$", overpayment);

That is not how you use printf.
System.out.printf("%1.2f and %d", 1.25f, 1000);
Knowing this, you can also add extra formatting:
printf( "$%.2f", overpayed );
Inside of the format string you can specify your data types, and then each one is passed as an argument thereafter.

Related

Calling toCelsius method in java

This Question is from my programming class:
In the convertFToC method, change the second System.out.println statement so it produces a display such as
212.0 degrees Fahrenheit is 100.0 degrees Celsius
for an input of 212. If you are baffled by this instruction, here is a fuller description:
The first half of the output line ( 212 degrees Fahrenheit is ) is already written. The next item to be displayed is
the number of degrees celsius, which is being calculated and returned by the toCelsius method.
Remember (see Lecture 3 and preparation exercises) that the result of a return method can be used elsewhere in
a program by calling its name and providing the correct number and type of input parameters.
Call the toCelsius method within the System.out.println statement, sending it the data that it needs (the variable representing the degrees in fahrenheit).
Finish off the statement by concatenating the string " degrees Celsius" on the end.
This program should now compile. If you run it, it will convert one value from Fahrenheit to Celsius.
The code is below, can someone show me how to call the to toCelsius method. thanks
import java.util.Scanner;
/**Lab 4 COMP160 2020
* Starting code*/
public class FahrenheitToCelsius{
public static void main(String[]args){
convertFToC();
convertFToC();
convertFToC();
//Step 5;
}
/**gets input from user representing fahrenheit and displays celsius equivalent*/
public static void convertFToC(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Fahrenhei temperature: ");
double fahrenheit = scan.nextDouble(); //Step 2 - assign next double input from Scanner object
System.out.println(fahrenheit + " degrees Fahrenheit is " + + " degrees Celsius"); //Step 4
}
/**calculates and returns the celsius equivalent of a double input parameter called fahr*/
public static double toCelsius(double fahr){
int BASE = 32;
double CONVERSION_FACTOR = 9.0/ 5.0;
double celsius = CONVERSION_FACTOR + BASE / fahr;//Step 3
return celsius;
}
}// end class
Add toCelsius(fahrenheit) between those two consecutive +s. And also correct the conversion formula in the method

Decimal Format in Jframe?

I am making a pizza calculator but my results come out as "$7.5" instead of "$7.50". I have this decimal format code written out with my code below it, but it doesn't seem to work. Any ideas?
private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
double diameter;
double labourCost = 1.00;
diameter = Double.parseDouble(diameterInput.getText());
double storeCost = 1.50;
double materialsCost = 0.50 * diameter;
double totalCost = labourCost + storeCost + materialsCost;
DecimalFormat x = newDecimalFormat("0.00");
costOutput.setText("The cost of the pizza is $" + totalCost);
You're not using the result ("x") of the operation for anything. I'm guessing that replacing "totalCost" with "x" in the last line will help?
You need to use a Decimal Formatter to convert your floating point value over to a string.
// Make a new formatter with your format
DecimalFormat myFormatter = new DecimalFormat("$##.00");
// Convert your number to a human readable string
String output = myFormatter.format(22.99999f);
System.out.println(output); // Prints $23.00
See this page for details on the various patterns https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

DecimalFormat.format method call: incompatible types

I wanted to know why there is an error and how to fix it for my java project.
I have to make exactly same out as these:
What is your annual interest rate as a decimal? (ex: 0.045): .033
How many years will your mortgage be held? 15
What amount of the mortgage did you borrow? 300000
The number 0.033 can be represented as 3.3%
The mortgage amount is $300,000.00
The monthly payment in dollars is $2,115.30
The total payment in over the years in dollars is $380,754.76
The over-payment is $80,754.76 The over-payment as a percentage of
the mortgage is 26.9
And this is what I did on Eclipse;
double annIntRat;
int nOY;
int borrowMor;
int M;
double monthPay;
double mIR;
Scanner scnr = new Scanner(System.in);
// Your code should go below this line
System.out.print("What is your annual interest rate as a decimal? (ex 0.045): ");
annIntRat = scnr.nextDouble();
System.out.print("How many years will your mortgage be held? ");
nOY = scnr.nextInt();
System.out.print("What amount of the mortgage did you borrow? ");
borrowMor = scnr.nextInt();
DecimalFormat df = new DecimalFormat("0.0");
System.out.println("\nThe number "+annIntRat+" can be represented as "+df.format((annIntRat)*100)+"%");
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
M=defaultFormat.format(borrowMor); //< Here is the error and tells me to change to String.But if I do so, there will be an error down there for monthPay=.....
System.out.println("The mortgage amount is "+M);
mIR=(annIntRat)/12;
monthPay=(mIR * M)/(1-(1/Math.pow(1+mIR,12*nOY)));
It took me a while to see where you highlighted your error, I would recommend being more explicit with where your errors are.
The 'format' method of NumberFormat you are using returns a type of String, which would explain your error.
The following should do the trick, although you can't be certain that a user is to input an integer...take that in mind.
M = Integer.parseInt(defaultFormat.format(borrowMor));
The DecimalFormat.format(long) method is an inherited method from the NumberFormat class — NumberFormat.format(long). The method returns an instance of String.
So, just use an instance of the String type to store and use the return value of the method:
String borrowMorString = defaultFormat.format(borrowMor);
System.out.println("The mortgage amount is " + borrowMorString);
// …
monthPay = (mIR * borrowMor) / (1 - (1 / Math.pow(1 + mIR, 12 * nOY)));

Formatting of double to not include decimal places

The code below is what I have. I am a fairly new programmer going through my first Java class so bear with me.
import salespersonannualcomp.SalespersonCompensationAnnualCalculator;
import java.util.Scanner;
public class SalespersonAnnualSalesInput
{
public static void main( String[] args)
{
Scanner input = new Scanner( System.in );
//Instantiates a new instance of SalespersonCompensationAnnualCalculator
SalespersonCompensationAnnualCalculator myAnnualSales = new SalespersonCompensationAnnualCalculator();
//Prompt for and input total annual sales
System.out.println( "Please enter the total annual sales:" );
String yearlySalesString = input.nextLine();
//Declares yearlySalesInt as the variable that will store the results of Integer.parseInt
int yearlySalesInt = Integer.parseInt(yearlySalesString);
//Declares calcResults as the variable that will store the value created by the calcAnnualCompensation method
double calcResults = myAnnualSales.calcAnnualCompensation(yearlySalesInt);
//Displays the result of the calculations done for determining total annual compensation
System.out.println(" Total Annual compensation is $"+ calcResults);
System.out.println();
System.out.println(" Total Potential Annual Compensation Chart");
for(double potentialAnnualSales = yearlySalesInt;potentialAnnualSales<=(1.5*yearlySalesInt);potentialAnnualSales=potentialAnnualSales+5000)
{
double calcAnnualCompensation=myAnnualSales.calcAnnualCompensation(potentialAnnualSales);
System.out.printf( "%f %f%n ",potentialAnnualSales,calcAnnualCompensation);
}
}
}
The resulting output looks like this.
Total Annual compensation is $60400.0
Total Potential Annual Compensation Chart
160000.000000 60400.000000
165000.000000 60725.000000
170000.000000 61050.000000
175000.000000 61375.000000
180000.000000 61700.000000
185000.000000 62025.000000
190000.000000 62350.000000
195000.000000 62675.000000
200000.000000 63000.000000
205000.000000 63325.000000
210000.000000 63650.000000
215000.000000 63975.000000
220000.000000 64300.000000
225000.000000 64625.000000
230000.000000 64950.000000
235000.000000 65275.000000
240000.000000 65600.000000
I would like for it to not display the decimal places, and for all the lines to align correctly. I have the output correct but I'm struggling with the formatting.
You are close...
If you want no places after the decimal, and to line it up:
System.out.printf( "%10.0f %10.0f%n ",potentialAnnualSales,calcAnnualCompensation);
If you want two places after the decimal:
System.out.printf( "%10.2f %10.2f%n ",potentialAnnualSales,calcAnnualCompensation);
Essentially, 10.2f means 10 spaces to the left of the decimal (using spaces for padding) and 2 after. Similarly, 6.0f would mean 6 spaces to the left of the decimal and none after. You'll have to play with the number of spaces for your specific use case.
Use either:
new DecimalFormat("#").format(d)
Or:
(int)Math.round(d)
In general using double's for monetary calculations is a bad practice. Instead use BigDecimal. To get rid of the trailing decimals call setScale(0); on your instance. For better formatting use NumberFormat.
You can tell printf how many decimal places to print as well as how wide to make each field. The syntax is like so: %<WIDTH>.<PRECISION>f where <WIDTH> and <PRECISION> are to be replaced by non-negative integers. Both numbers are optional and you can leave them out if you want the defaults.
Here I am printing some random numbers with column width of 10 characters and a precision of 2 decimal places.
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 6; ++i) {
System.out.printf("%10.2f%10.2f%10.2f%10.2f%n",
100000.0 * Math.random() * Math.random(),
100000.0 * Math.random() * Math.random(),
100000.0 * Math.random() * Math.random(),
100000.0 * Math.random() * Math.random());
}
}
}
Possible Output:
72411.07 11074.66 4722.24 74523.64
264.89 54015.77 53969.66 61229.94
5386.74 7939.65 47678.67 24953.68
4985.14 17769.77 17345.57 38392.68
4841.93 4103.14 3581.99 74036.73
52477.30 1846.34 35547.62 10065.36
If I change the format specifiers from %10.2f to %10.0f it will only print the integral part and I might get the following output instead:
42116 26756 3293 7957
1693 23516 83116 39032
3981 40417 53635 19735
53504 77468 12341 16178
4424 81325 79304 5460
23825 6004 16507 37537
For more advanced features of printf, see the documentation of java.util.Formatter.

(double,int) cannot be applied to (double)

Been wracking my brain for hours trying to figure this out.
i have the main method which is:
public static void main(String [] args)
{
double payRate;
double grossPay;
double netPay;
int hours;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Pay Roll Program");
printDescription();
System.out.print("Please input the pay per hour: ");
payRate = input.nextDouble();
System.out.println("\nPlease input the pay per hour: ");
hours = input.nextInt();
System.out.println("\n");
netPay = computePaycheck(netPay);
System.out.println("The net pay is $" + (netPay));
System.out.println("We hope you enjoyed this program");
System.exit(0);
and the method that calculated the netPay
public static double computePaycheck(double payRate, int hours)
{
double grossPay = computePaycheck(payRate*hours);
double netPay = (grossPay - (grossPay *.15));
return netPay;
}
But I'm getting the error "computePaycheck(double,int) in PayCheck cannot be applied to (double)"
I sort of understand this, but I can't for the life of me figure out a remedy.
1) You are calling a function with 2 parameters while only passing 1. That will cause a compilation error.
2) When you call computePaycheck from within itself that will loop and cause a stack overflow.
netPay = computePaycheck(netPay);
public static double computePaycheck(double payRate, int hours)
"computePaycheck(double,int) in PayCheck cannot be applied to (double)"
Your method takes two parameters, a double and an int.
You can only call it with those two (you are missing the number of hours in the call).
netPay = computePaycheck(payRate, hours);
double grossPay = payRate*hours;
In your computePaycheck method, you have the following line:
double grossPay = computePaycheck(payRate*hours);
This is passing one parameter (the product of payRate and hours) to the computePaycheck function, which requires two parameters. It looks like you meant to say:
double grossPay = computePaycheck(payRate, hours);
But you will need to be careful! This will cause your program to recur infinitely! You will need to determine how to calculate the gross pay without calling this function, since if you do call it recursively within itself, there is no condition from which it will return.
Your method takes two parameters -- double payRate and int hours, but you are only specifying a double when you call computePaycheck in your main method.
It's not clear what you intend to happen, but the mismatched parameters should let you know what is wrong with your program.
The first statement of your computePaycheck method calls computePaycheck with a single parameter (a double) whereas the computePaycheck takes 2 parameters (a double and an int). That is why your code fails to compile.
If you "fix" this by using double grossPay = computePaycheck(payRate, hours); instead, this will compile BUT you will get infinite recursion! Don't you simply want to do double grossPay = payRate*hours; ?
It's clear that you set 2 parameters but from the main class you are only calling just one parameter. You should find a way to call the 2 parameters at the same time.

Categories