简体   繁体   中英

How to parse an integer, when I have a format for a double?

I'm taking user entries from my database, which stores the values user entered that might be either float or int, but my code meant to check the following condition

String pattern = "###,###.##";
        DecimalFormat decimalFormat = new DecimalFormat(pattern);
if (!userput.equals("")){
        resultoutput.setText(""+Double.parseDouble(userput)*Double.parseDouble(decimalFormat.format(Double.parseDouble(x[1]))));}
        else{
            userinput.setText("1");
            resultoutput.setText(""+Double.parseDouble(decimalFormat.format(Double.parseDouble(x[1]))));
        }

So when it encounters int it crashes. For example, for 13152 it gives java.lang.NumberFormatException: Invalid double: "13,152"

Moreover if i get the output as something like this 13170.00 i get the error as follows java.lang.NumberFormatException: Invalid double: "13,170.00"

Sometimes the values fetched from the database contains float and sometimes integer, here x[1] is the currency exchange rate and userinput contains integer or float ....lets say i am trying to get usd to idr currency so i get 13170.00 which is not double neither int because i get this error java.lang.NumberFormatException: Invalid double: "13,170.00"

It's double , because it contains . and doesn't contain f or F suffix.

From Java Tutorials :

The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d ( 64-bit double literal; this is the default and by convention is omitted ).

double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1  = 123.4f;

Your problem is not in whether the number is integer or double. Your problem lies in the fact that your conversion rate has more than three digits.

This is your code for displaying the value (reformatted):

resultoutput.setText(
    ""
    + Double.parseDouble(userput)
    * Double.parseDouble(decimalFormat.format(Double.parseDouble(x[1]))));

So, you are:

  1. Taking your exchange rate, which is a string, and converting it to double.
  2. Taking the resulting double, and converting it back to string, using a decimal format.
  3. Taking that formatted text, and converting it again to double
  4. Multiplying it by the double value of the user input
  5. Converting the result to a string (without formatting).

The problem lies in step 2 and 3. They are actually unnecessary. But for some numbers they will work.

Your format is ###,###.## . Let's see how some numbers look when they are formatted with this format:

╔═════════╤═══════════╗
║ number  │ formatted ║
╠═════════╪═══════════╣
║ 0.273   │ 0.27      ║
╟─────────┼───────────╢
║ 5.3     │ 5.3       ║
╟─────────┼───────────╢
║ 358.2   │ 358.2     ║
╟─────────┼───────────╢
║ 10.0    │ 10        ║
╟─────────┼───────────╢
║ 1298.52 │ 1,298.52  ║
╚═════════╧═══════════╝

So, when you have conversion rates that are smaller than four digits to the left of the decimal point, the decimalFormat.format() call converts them to a string that is still a legal Java double. So when you then call Double.parseDouble on this string in step 3, everything is good.

But when you have a large number, such as "13152.00" , what you do is:

  1. Convert it into double: 13152.0
  2. Convert it into string with a format: 13,152.0
  3. Convert it into double: - this doesn't work. Java is not accepting , in the input for Double.parseDouble() .

So really, your conversion should just be:

resultoutput.setText(
    ""
    + Double.parseDouble(userput)
    * Double.parseDouble(x[1]));

This will give you a proper, unformatted number in your resultoutput , without throwing your an exception.

I'm pretty sure you intended the decimalFormat in order to display the number, not in order to convert it again and again. This means you should only use it on the result of the conversion - instead of doing "" + ... , which gives you just default formatting.

resultoutput.setText(
    decimalFormat.format( Double.parseDouble(userput) * Double.parseDouble(x[1])));

Be warned, though, that you will not see two digits after the decimal point with your format - it will display 10.0 as 10 . If you want to always display two digits, you have to use ###,##0.00 as your format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM