Link to home
Start Free TrialLog in
Avatar of cakirfatih
cakirfatih

asked on

Convert 1,000 to 1000

I am writting an EJB that sits on top of a third party software. This EJB has to be Generic

I get a string from the 3-rd party tool in the form of 1,000. I need to convert this back to 1000 (without the comma).

Is there any way of doing this without any Array stuff. Anyone aware of a Jakarta-commons library or somethins that I can use to do this.
Remember this has to be generic.

Thanks in advance
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

s = s.replaceAll(",", "");
Avatar of cakirfatih
cakirfatih

ASKER

It has to be generic,
If s = "hi, nice to meet you"
The comma will be gone I dont need that.
Thanks
That is
What do you mean ?
What i posted *is* generic
If the string you are receiving will always be an integer that may or may not contain a comma, you can use the NumberFormat class to convert it such that the comma is removed:

String str = "1,000";
NumberFormat fmt = NumberFormat.getInstance();
Number num = fmt.parse(str);
String newStr = Integer.toString(num.intValue());

newStr would end up being "1000" in this case.

I hope that helps.
The string I will be receiving may not always be an integer.
Anything I can do to test wether it is or not prior to the conversion to Number
Thanks
If I'm understanding properly, you want to remove the commas in formatted integers but not in text.  If so, then why not try something like this?

public String convertString(String str)
{
      String result = null;

      try
      {
            if(str != null)
            {
                  NumberFormat fmt = NumberFormat.getInstance();
                  Number num = fmt.parse(str);

                  result = Integer.toString(num.intValue());
            }
      }
      catch(ParseException e)
      {
            result = str;
      }

      return result;
}

If you pass "1,000" to this method, it will return "1000".
If you pass "hi, nice to meet you" to this method, it will return "hi, nice to meet you".
If you pass null to this method, it will return null.

I hope that helps.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you need to treat null input:



      public static String convertString2(String s) {
            return s != null? s.replaceAll("(?<=\\d),(?=\\d)", "") : null;
      }
:-)