Jump to content

NumberFormat

- - - - -

  • Please log in to reply
1 reply to this topic

#1
nicckk

nicckk

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 629 posts
I solved my problem, I was trying to parse the converted double, that had the dollar sign and commas, I fixed it by just formatting it in the showTable method.
---------------------------------------------------------------------------------------------------------------------
I'm having problems with a static method. I'm trying to return a double after formatting a double with NumberFormatter; which returns a String. I'm trying to use the parseDouble method in the Double class but I get an error. My code is:


import java.text.NumberFormat;


public class Loop2

{

	public static void main(String[] args)

	{

		showTable(1000, 0.12, 12);

		System.out.println("\n*********************\n");

		showTable(5000, 0.10, 60);

	}

	

	public static void showTable(double borrowed, double yearlyRate, int months)

	{

		System.out.println("Ammount Borrowed " + borrowed);

		System.out.println("Yearly Intrest Rate " + yearlyRate);

		System.out.println("Number of Months " + months + "\n");

		System.out.println("Total Due is " + amountDue(borrowed, (yearlyRate / 12), months));

	}


	public static double amountDue(double principal, double monthlyRate, int period) //Error here

	{

		NumberFormat formatter = NumberFormat.getCurrencyInstance();

		double amountDue = Double.parseDouble(formatter.format(principal * Math.pow(1 + monthlyRate, period)));

		return amountDue;

	}

}


And my error is :

Exception in thread "main" java.lang.NumberFormatException: For input string: "$1,126.83"

	at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)

	at java.lang.Double.parseDouble(Unknown Source)

	at Loop2.amountDue(Loop2.java:31)

	at Loop2.showTable(Loop2.java:21)

	at Loop2.main(Loop2.java:7)



#2
discomonk

discomonk

    Newbie

  • Members
  • Pip
  • 7 posts
nicckk,

a valid double string for parseDouble() to recognize would be something like "1126.83", so the currency format "$1,126.83" is not a valid and therefore the exception. I would suggest you to make the following changes:


	public static void showTable(double borrowed, double yearlyRate, int months)
	{
		//.......
		System.out.println("Total Due is " + currencyFormat(amountDue(borrowed, (yearlyRate / 12), months)));
	}

	public static double amountDue(double principal, double monthlyRate, int period) //Error here
	{
                return principal * Math.pow(1 + monthlyRate, period);
	}

        public static String currencyFormat(double val) {
		NumberFormat formatter = NumberFormat.getCurrencyInstance();
		formatter.format(val);
        }






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users