Can anyone help me remove the comma from my output? [duplicate] - java

This question already has answers here:
how to print a Double without commas
(10 answers)
Closed 7 years ago.
So my code is correctly outputting the compounded interest periodically, but it is putting my output with a comma. Ex: $1,000.00 I would like the answer to be: $1000.00.
Here is my code guys:
package certificatedeposit;
public class CertificateDeposit {
public static void main(String[] args) {
double PV = 1000.00;
System.out.printf("Enter annual rate: ");
java.util.Scanner in = new java.util.Scanner( System.in );
double rate = in.nextDouble( );
double rates = rate / 100 / 12;
System.out.printf("Enter CD term in months: ");
int months = in.nextInt( );
double product = ( 1 + rates);
double exp = Math.pow(product,months);
double fv = PV * exp;
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%,.2f \n", rate, fv);
}
}

I had changed the code for you but as #ajb said in comment, you are getting "," because you have used it while formatting string. For deep understanding read here
package certificatedeposit;
public class CertificateDeposit {
public static void main(String[] args) {
double PV = 1000.00;
System.out.printf("Enter annual rate: ");
java.util.Scanner in = new java.util.Scanner( System.in );
double rate = in.nextDouble( );
double rates = rate / 100 / 12;
System.out.printf("Enter CD term in months: ");
int months = in.nextInt( );
double product = ( 1 + rates);
double exp = Math.pow(product,months);
double fv = PV * exp;
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%.2f \n", rate, fv);
}
}

Remove the comma from the format string for variable fv:
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%.2f \n", rate, fv);
Also here is a discussion about using different (not only comma) symbols for grouping separator.

Related

using the NumberFormat import in System.out.format

I'm doing a program on compound interest for a school assignment. I tried using System.out.format(); and used money.format to format the variables investment, interest, and investTotal. I don't know why but it keeps on throwing me an error for
"Invalid value type 'String' for format specifier '%.2f', parameter 2, 3, and 4" I've been trying to figure this out for quite a while now and I still can't seem to find why it is.
-- A
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// SPLASH
// CONSTANT
// OBJECT
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// VARIABLES
double investment;
double investTotal;
double rate;
double intrest;
int year;
// INPUT
do
{
System.out.print("Enter yearly investment (min $100.00 deposit): ");
investment = input.nextDouble();
}
while (investment < 100);
do
{
System.out.print("Enter intrest rate (%): ");
rate = input.nextDouble()/100;
}
while (rate <= 0);
do
{
System.out.print("Enter number of years: ");
year = input.nextInt();
}
while (year <= 0 || year > 15);
// PROCESSING
investTotal = investment;
for (int perYear = 1; perYear <= year; perYear++)
{
intrest = investTotal*rate;
investTotal = (investment+intrest);
System.out.format("%2s | %.2f | %.2f | %.2f\n", perYear, money.format(investment), money.format(intrest), money.format(investTotal));
investTotal = investTotal + investment;
}
// OUTPUT
}
}
getCurrencyInstance returns a String and therefor can't be formatted using %.2f.
You better look how NumberFormat works:
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
As you can see, the result of the formatting is a String, when you are using String.format with %.2f you should enter a number e.g:
System.out.format("%2s | %.2f\n", 1.001, 1.005);
I'm not sure what are you trying to get using the NumberFormat, if you classify I will be able to help you further with this question.

Can't use decimals in scanner input [duplicate]

This question already has answers here:
Scanner double value - InputMismatchException
(2 answers)
Closed 5 years ago.
I have this code here:
import java.util.Scanner;
public class Loan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter annual interest rate, e.g., 7.35%: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = annualInterestRate / 1200;
System.out.print("Enter number of years as an integer, e.g., 5: ");
int numberOfYears = input.nextInt();
System.out.println("Enter loan amount, e.g., 120000.95:" );
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow
(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12;
System.out.println("The monthly payment is $" +
(int)(monthlyPayment * 100) / 100.0);
System.out.println("The total payment is $" +
(int)(totalPayment * 100) /100.0);
}
}
The annualInterestRate is a double value but when i try to enter a decimal like 5.4, i get an error. Using whole numbers works perfectly fine.
Anything wrong with the code? Thanks:)
Your locale (Norway) use , as decimal delimiter as it is specified in the list of Oracle looks like :
4.294.967.295,000
As the doc sais :
A scanner's initial locale is the value returned by the Locale.getDefault()
But you can change the Scanner locale with useLocale(Locale) like this :
Scanner sc = new Scanner(ystem.in);
sc.useLocale(Locale.ENGLISH);
As said by the doc
It may be changed via the useLocale(java.util.Locale) method
This will accept a . as delimiter.
The full documentation is here

Looking for a way to keep two decimal places without rounding up

I have to display my outputs with two decimal places and the program outputs should be 205.16 for monthly payment and 12309.91 for total payment. Before using decimal format to round the answers where correct but after rounding to two decimal places the outputs are now .01 to high. What can I do to remove the extra decimal places without rounding up .01?
import javax.swing.*;
import java.text.*;
/**
*DriverMortgageClass
*/
public class DriverMortgageClass
{
public double annualInterestRate;
public int numberOfYears;
public double loanAmount;
public double monthlyPayment;
public double totalPayment;
public double monthlyInterestRate;
DecimalFormat fmt = new DecimalFormat ("0.00");
//main method
public static void main(String[] args) {
new DriverMortgageClass().start();
}
//declare private mortgage object
private Mortgage mortgage;
public DriverMortgageClass()
{
mortgage = new Mortgage();
}
public void start()
{
//get input for interest rate
String annualInterestRateString = JOptionPane.showInputDialog(null,"Enter yearly interest rate, for example 8.5",JOptionPane.QUESTION_MESSAGE);
annualInterestRate=Double.parseDouble(annualInterestRateString);
mortgage.setAnnualInterestRate(annualInterestRate);
//get input for number of years
String numberOfYearsString = JOptionPane.showInputDialog(null,"Enter number of years as an integer, for example 5",JOptionPane.QUESTION_MESSAGE);
numberOfYears= Integer.parseInt(numberOfYearsString);
mortgage.setNumberOfYears(numberOfYears);
//set loan amount
String loanAmountString = JOptionPane.showInputDialog(null,"Enter loan amount, for example 10000.00",JOptionPane.QUESTION_MESSAGE);
loanAmount= Double.parseDouble(loanAmountString);
mortgage.setLoanAmount(loanAmount);
//Invoke monthly and total payment
monthlyInterestRate=annualInterestRate/1200;
monthlyPayment=loanAmount*monthlyInterestRate /(1-(Math.pow(1/(1+monthlyInterestRate),numberOfYears*12)));
totalPayment=monthlyPayment*numberOfYears*12;
//display monthly and total payment
JOptionPane.showMessageDialog(null,"The monthly payment is"+ " " + fmt.format(monthlyPayment)+'\n'
+"The total payment is"+ " " + fmt.format(totalPayment));
System.exit(0);
}
}
Use DecimalFormat.
DecimalFormatt df = new DecimalFormat( "#.00" );
df.format(1.478569); // 1.48
Don't want the rounding up?
double c = 1.478569d;
c = (double)((long)(c*100))/100; // 1.47
The double casting way might overflow [Jonny Henly noted below]. Beware. :)
There are numerous ways of doing this. Alternatively,
df = new DecimalFormat( "#.000" );
String num = df.format(1.478569);
num = num.substring(0, num.length()-1); // 1.47
Does it help?
You can use RoundingMode.FLOOR like that
for Kotlin
number.toBigDecimal().setScale(2,RoundingMode.FLOOR).toDouble()
for JAVA
new BigDecimal("1.555").setScale(2, RoundingMode.FLOOR);

Proper Formatting

I have the program working I just need help cutting off the extra numbers, Im not very skilled at using the printf statements when printing in Java. When I run it I get output like 1225.043 Here is what I have:
import java.util.Scanner;
public class Comparison {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
float amount;
double principal = 1000.00;
double rate;
System.out.println("Enter interest rate");
rate = keyboard.nextDouble();
System.out.println("Year" +" "+ "Amount on deposit");
for(int year = 1; year <= 10; ++year)
{
amount = (float) (principal * Math.pow(1.0 + rate, year));
System.out.println(year+ " "+ amount);
System.out.println();
}
}
}
Try
System.out.printf("%2d %.2f%n", year, amount);
Output:
Enter interest rate
0.1
Year Amount on deposit
1 1100.00
2 1210.00
3 1331.00
4 1464.10
5 1610.51
6 1771.56
7 1948.72
8 2143.59
9 2357.95
10 2593.74

monthly payment calculator

I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}

Categories

Resources