Java number format exception. - java

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "P35.00"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at OrderSystems.OrderSystem.jButton3MouseClicked(OrderSystem.java:419)
at OrderSystems.OrderSystem.access$900(OrderSystem.java:14)
at OrderSystems.OrderSystem$10.mouseClicked(OrderSystem.java:241)
I keep getting this error after i clicked the jButton3. heres my codes.
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
double sub = Double.parseDouble(sub_field.getText());
double vat = Double.parseDouble(vat_field.getText());
double allTotal = (sub + vat);
String iTotal = String.format("%.2f", allTotal);
total_field.setText(iTotal);
}
This is the code for the sub_field and vat_field
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
double ham = Double.parseDouble(ham_field.getText());
double burger = Double.parseDouble(burger_field.getText());
double bacon = Double.parseDouble(bacon_field.getText());
double bac = bacon * 5;
double harm = ham * 10;
double burg = burger *20;
double sub = harm + burg + bac;
String sub_com = String.format("P%.2f", sub);
sub_field.setText(sub_com);
}

java.lang.NumberFormatException is pretty clear: "P35.00" is not a number.
This Exception is thrown when the paramether for the parsing Double.parseDouble is not what it is excpecting.
Try out removing the P from 35.00 and see if it works.
It is also common practice to surround it with a try-catch block to prompt to the user what went wrong.

It is crashing because your input string is "P35.00" and you try to parse that into a double. Remove the 'P' and it should work because the compiler will not parse a P into a double.

Related

How to convert string with $ sing in it to int

I have a string "$1,076.00" and I want to convert them in to int,
I capture some value $1,076.00 and saved in string called originalAmount,
and tried int edited = Integer.parseInt(originalAmount); and it gave me error java.lang.NumberFormatException: For input string: "$1,076.00"
can anyone help?
You need to remove the undesired part ($ sign) and then parse the string to double carefully since the decimal part is a locale dependent
String pay = "$1,076.00";
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse(pay.replace("$", ""));
double result = number.doubleValue();
System.out.println(result);
string sourceString = "$1,076.00";
sourceString.substring(1, sourceString.length() - 1)
int foo = Integer.parseInt(sourceString);
Try this:
String amount = "$1,076,.00";
String formatted = amount.replace("$", ""); // remove "$" sign
formatted = formatted.replace(",", ""); // remove "," signs from number
double amountDouble = Double.parseDouble(formatted); // convert to double
int amountInt = (int)amountDouble; // convert double value to int
System.out.println(amountInt); // prints out 1076
String originalAmount="$1076.00";
String amount = originalAmount.replace($,"");
int edited = Integer.parseInt(amount);
Thanks everyone yr answers help me a lot
I have come up with
originalAmount = originalAmount.substring(1);
if (originalAmount.contains("$")) {
originalAmount = originalAmount.replace("$", "");
}
newOriginalAmt = Double.parseDouble(originalAmount);
System.out.println(newOriginalAmt);
pls let me know yr thoughts

Conversion of double to string gives exponent values

I am trying to convert a string 32,646,513.32 to a double and then convert it to a string in scientific notation like this 3.264651332E7. The code below is
double amount = 0;
for (Payments payments : pvor.getPayments()) {
payments.setDocumentNumber(pvor);
amount += Double.parseDouble(payments.getAmount());
payments.setDate(new Date());
}
DecimalFormat df = new DecimalFormat("#.00");
double totalAMount = Double.valueOf(df.format(amount));
Double totalAMounts = (Double) totalAMount;
pvor.setAmount(String.valueOf(totalAMounts.doubleValue()));
How do I display large numbers in same format as I give?
Instead of using just String.valueOf(totalAmounts), which give you number in exponential format, you need to format your double value to match the string format that you want. Try something like new DecimalFormat("#,###.00").format(totalAmounts). Or simply use String.format("%,.2f", totalAMounts).
If I understood your problem correctly then you do not need String.valueOf() but String.format().
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String input = "32,646,513.32";
double value = Double.parseDouble(input.replace(",",""));
String output = String.format("%f",value);
System.out.println("Value: " + output);
}
Output:
Value: 32646513.320000
Replace the following line in your code appropriately:
/* Note the change from `valueOf()` to `format()` */
pvor.setAmount(String.format("%f",totalAMounts.doubleValue()));

Error when typing error number

Someone can explain my problem? When i try inputting comma number, i always get
Exception in thread "AWT-EventQueue-0"
java.lang.NumberFormatException: For input string: "1.2"
my code:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String showInputDialog = JOptionPane.showInputDialog("Enter Line: ");
int liningg = Integer.parseInt(showInputDialog);
double volume = liningg*liningg*liningg;
JOptionPane.showMessageDialog(null, "Last result are: "+volume );
}
NumberFormatException For input string: "1.2"
"1.2" is not an integer, so it can't be parsed as an integer value.
Maybe you want:
double liningg = Double.parseDouble(showInputDialog);

Is there any short and better way to parse a string to Double with exceptions handled?

This is the code that i have written to get the text from the textboxes, parse them to double datatype, and print their product. So, is there any alternative for parsing a string to double with its exceptions handled..?
...........
public void actionPerformed(ActionEvent ae){
try{
if(ae.getSource()==b1 || ae.getSource()==t2){
String s1=t1.getText();
String s2=t2.getText();
double x=Double.parseDouble(s1);
double y=Double.parseDouble(s2);
double z=x*y;
t3.setText(""+z);
}
if(ae.getSource()==b2){
t1.setText(null);
t2.setText(null);
t3.setText(null);
t1.requestFocus(true);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(this,"Please Enter Proper Number in the TextFields");
}
}
...............
String s1 = t1.getText();
try {
double x = Double.parseDouble(s1);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,"Please Enter Proper Number in the t1 TextField");
return;
}
String s2 = t2.getText();
try {
double y = Double.parseDouble(s2);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,"Please Enter Proper Number in the t2 TextField");
return;
}
It is you who knows how to handle such exceptions in your case. There is no other ways around to get the exceptions handled for you. Your code is correct and that is what done by most programmers. You may use JFormattedTextField but however that also doesn't handle exceptions for you.
IMHO No,
If you see Docs
public static double parseDouble(String s)
throws NumberFormatException
even if any shortcut is there it will use the above method and apperently thats also throws the same exception.
To avoid handling exceptions while parsing strings to get numbers (or double, in your case), you can use NumberFormat in conjunction with ParsePosition as shown below:
import java.text.NumberFormat;
import java.text.ParsePosition;
public class TestClass
{
public static void main(String[] args)
{
System.out.println("Parse test 10.00 ---> " + parseNumber("10.00"));
System.out.println("Parse test \"\" ---> " + parseNumber(""));
System.out.println("Parse test 10 ---> " + parseNumber("10"));
System.out.println("Parse test shgdfhsaghdga ---> " + parseNumber("shgdfhsaghdga"));
}
private static boolean parseNumber(String input)
{
NumberFormat fmt = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
fmt.parse(input, pos);
return input.length() != 0 && (input.length() == pos.getIndex());
}
}
OUTPUT
Parse test 10.00 ---> true
Parse test "" ---> false
Parse test 10 ---> true
Parse test shgdfhsaghdga ---> false
If the number is a valid string, the index of the ParsePosition object will reach the end of the string. Otherwise, it will end at the first invalid position. The last return statement checks this condition. You can use the parseNumber() method to prevalidate your string before parsing it to double.

Reading from the File

This program has 2 classes with a main method and is supposed to read from a file. My problem is that the line double listPrice = fileScan.nextDouble(); gives an error exception like this Exception in thread "main" java.util.InputMismatchException. The error is in this class:
Here is contents of the file:
Honda Accord
2004 16780.00 10.0
Chrysler SUV
2002 8600.00 0.0
Toyota Camry
2007 21799.99 3.0
Ford Escort
2006 12345.78 5.5
//note there is no space between each line
class Proj1P2CarAryListService
{
private ArrayList<Proj1CarData> carList = new ArrayList<Proj1CarData>();
public Proj1P2CarAryListService()
{
carList = new ArrayList<Proj1CarData>();
}
public void readStoreCarsData()
{
Scanner scan = new Scanner(System.in);
Scanner fileScan;
boolean validName = false;
double discountAmount;
double netPrice;
do
{
System.out.print("Enter file name: ");
String str1 = scan.nextLine();
try
{
fileScan = new Scanner(new File(str1));
validName = true;
while (fileScan.hasNext())
{
String name = fileScan.nextLine();
String modelYear = fileScan.next();
double listPrice = fileScan.nextDouble();
double percentDiscount = fileScan.nextDouble();
discountAmount = listPrice * percentDiscount/100.0;
netPrice = listPrice - discountAmount;
Proj1CarData proj1 = new Proj1CarData(name, modelYear, listPrice, percentDiscount, discountAmount, netPrice);
carList.add(proj1);
System.out.println(proj1.toString());
}// end while
}// end try
catch (FileNotFoundException fnfe)
{
System.out.println("Invalid File name; enter again");
}
} while (!validName);
}//readStoreCarsData
This exception is thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type(Double must be separated by . or , like said jlordo), or that the token is out of range for the expected type. Perhaps it is a file content problem.
The nextDouble() method of Scanner is locale-aware (see Documentation).
This means, if your locale is set to a country where '.' seperates a floating point number following would be a parsable double value: 123.456 while following number will give you a InputMismatchException 123,456. In Europe 123,456 would work, and 123.456 would throw an Exception. Hope it helps...
You might want to consider printing out each line. You might be getting more than you expect.

Categories

Resources