简体   繁体   中英

Replace " in Java String to Get Integer value from it

I have a String/Value "2.450,00 . I want to get the Integer value from it. For that, I need to remove the " in front of the 2 .

First you want to remove the comma sign and the decimals since an int (Integer) is a whole number.

str = str.split(",")[0];

This will split the string on the "," and take the first index which contains the string "2.450". Then you want to remove the punctuation. This can be done by replacing everything which is not a number with an empty space "".

str = str.replaceAll("[^0-9]", "");

Lastly, you want to convert the string to an integer.

int strAsInt = Integer.parseInt(str);

Full code:

public static void main(String[] args) {
    // The initial value
    String str = "2.450,00";

    str = str.split(",")[0];

    str = str.replaceAll("[^0-9]", "");

    int strAsInt = Integer.parseInt(str);

    // This will print the integer value 2450
    System.out.println(strAsInt);
}

One liner:

int stringAsInt = Integer.parseInt(str.split(",")[0].replaceAll("[^0-9]", ""));

Try the below snippet. Use substring method to remove "

public static void main(String[] args) {
  String str = "\"2.450,00";

  // prints the substring after index 1 till str length
  String substr = str.substring(1);
  System.out.println("substring = " + substr);

}

At first, you need to remove any non-digit character (excluding the '.' and ',' characters) from the input string, the regex "[^\\d\\,\\.]" may help you with this:

final String inputString = "Total: 100.000,05$";
final String numberString = inputString.replaceAll("[^\\d\\,\\.]", "");

The next step is a formatting digit string into a valid double form. At this step, you'll need to replace '.' with an empty string and the ',' with a dot '.' .

final String formattedNumberString = numberString
                                      .replace(".","")
                                      .replace(',', '.');

And, in the end, you are finally able to parse a valid number:

double inputNumber = Double.parseDouble(formattedNumberString);

(1) Remove double quote from string

String str = "\"2.450,00";

str = str.replace("\"", "")

(2) then you should replace the comma as well

str = str.replace(",", "")

(3) Finally you should use the Integer.parseInt() method to convert String to Integer

int i = Integer.parseInt(str);

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