-4

Can anyone help me to convert a string with both number and character to an integer in Java?

For example, I want to convert a String amount = $100.00 to an int.

I tried to use an integer.parseInt(); but it is giving an error.

String Checkamount = $1400.00; //Convert web element to string.
int intAmount = Integer.parseInt(Checkamount);

Expected result: 1400.00

Error message

Exception in thread "main" java.lang.NumberFormatException: For input string: "$1,400.00" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)

Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
Antony
  • 3
  • 2
  • 1
    Your expected result of `1400.00` isn't an `int`. – Jacob G. Sep 05 '19 at 00:27
  • You could start by calling `replaceAll` on the string, to remove the dollar sign. Remember to escape the dollar sign from the regular expression parser (use `"\\$"`). Also, I doubt whether you really want to use `int` - it looks like you're dealing with values that may contain non-whole amounts. – Dawood ibn Kareem Sep 05 '19 at 00:31
  • 2
    `NumberFormat.getCurrencyInstance(Locale.US).parse("$1,400.00").doubleValue()` – Andreas Sep 05 '19 at 00:37

6 Answers6

1

First off, 1400.00 can not be converted to int because it has decimal places. You need to use the variable type double or float to store this value.

Use Java's replace() to replace out the unwanted characters before converting to a number. Ex.

amount = amount.replace('$', '').replace(',', '');
double doubleAmount = Double.parseDouble(amount);

There's a cleaner way to do the replacement using a proper regex, but this should work.

jacob13smith
  • 919
  • 5
  • 12
  • Hi, Thanks for your reply. I have tried this but it showing an error as below Exception in thread "main" java.lang.NumberFormatException: For input string: "1 415.00" at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054) at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122) at java.base/java.lang.Float.parseFloat(Float.java:461) at anzTesting.testing.login(testing.java:34) – Antony Sep 05 '19 at 01:09
  • @Antony `1 415.00` has a space in it instead of `,` - to get a better response, you need to be clear in your expected inputs (and outputs ;)) – MadProgrammer Sep 05 '19 at 02:00
  • my sample code is here I using getting the input from my bank account using selenium web driver. [Sample code](https://codeshare.io/5XY1nE). – Antony Sep 05 '19 at 06:46
  • Make sure you are replacing the characters with empty characters, not spaces. I think you might be using `' '` instead of `''` – jacob13smith Sep 05 '19 at 20:17
0
import java.util.regex.Pattern;
import java.util.Locale;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class DollarToInt{
    public static void main(String[] args) throws ParseException{
        //Method 1 --> ERROR WHEN \n incl
        String amount="$1,32423410.00"; 
        amount=amount.replace("$", "").replace(",", "");
        double toDouble= Double.parseDouble(amount);

        //Method 2 --> IGNORES \n
        String amount2 = "$1,2131000.00";
        DollarToInt method2= new DollarToInt();
        BigDecimal toBigDecimal=method2.parse(amount2, Locale.US);

        //Method 3 -> WHEN \n incl REMOVES VALUES RIGHT OF \n
        Double toDouble3= NumberFormat.getCurrencyInstance(Locale.US).parse("$1, 400.00").doubleValue();

        System.out.println(toDouble); //M1
        System.out.println(toBigDecimal); //M2
        System.out.println(toDouble3); //M3
    }

     public BigDecimal parse(final String amount, final Locale locale) throws ParseException {
        final NumberFormat format = NumberFormat.getNumberInstance(locale);
        if (format instanceof DecimalFormat) {
            ((DecimalFormat) format).setParseBigDecimal(true);
        }
        return (BigDecimal) format.parse(amount.replaceAll("[^\\d.,]",""));
    }
}

I've tried two ways to parse the dollar format and I think method 2 works better and is the better way. Refer to : Converting different countrys currency to double using java

Turtle SK
  • 29
  • 6
0

Use substring.

String value = amount.substring(1,amount.length());

the "value" will now only store the number without dollar sign.

 double doubleAmount = Double.parseDouble(value);

i think this will help.

javaNoob
  • 86
  • 1
  • 9
0

Here the thing 1400.00 can not be converted to int. But if you want without decimal point then here is the complete solution

    String amount = "$1400.00";
    amount = amount.replace('$', ' ');
    int intAmount= (int)Double.parseDouble(amount);
sandip
  • 129
  • 5
  • Sorry it was my mistake, I was trying to convert to double. [This is the link for my sample code](https://codeshare.io/5XY1nE) – Antony Sep 05 '19 at 06:53
0

One possible solution is to make use of NumberFormat - the only restriction to this is making sure you're using an appropriate Locale

For example...

NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US);
try {
    Number number = formatter.parse("$1000.40");
    System.out.println(number);
    System.out.println(number.intValue());
    System.out.println(number.doubleValue());
} catch (ParseException ex) {
    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}

Will print

1000.4
1000
1000.4

You could also us an input of $1,000.40 and it would give you the same results.

Again, the caveat here is, the NumberFormatter will expect the input to be the same as it's output. For example, the above NumberFormatter will output a double value of 1000.6 as $1,000.60

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0
  • Amount of money must not be stored in Integer.
  • Amount of money should be stored in BigDecimal to keep accuracy. (ref)

To work with a currency string, you can use NumberFormat with locale.

public static void main(String[] args) {
    Locale locale = new Locale("en", "US");

    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);

    try {
        String input = "$123,456,56.2";
        Number money = currencyFormat.parse(input);
        BigDecimal moneyAmount = BigDecimal.valueOf(money.doubleValue());
        //Do whatever you want with money amount here.
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
}