# Function to convert String to Decimal value?

I need to convert `String` into `Decimal`. the isNumeric() method is retuning `false` if value is `Decimal`. Another alternate:

``````try
{
Integer x = Integer.valueOf(myString);
}
catch (exception e)
{
// it's not an Integer, try something else
}
``````

Is there any other way to convert `Decimal` into `String`?

Note: value which is coming can be `Integer` or `String`.

• What part of this are you actually having trouble with? Are there any examples that aren't working? The documentation is pretty clear on what you can do with Decimals/Integers/Strings. – Nick Cook Dec 17 '15 at 6:16
• Nick thanx for comment. i wanted to check is string is having Numeric value or Decimal value. i dont want to use Try Catch. is there anything else which i can try? my code is like this `if (searchKey.isNumeric() && Decimal.valueof(searchKey.trim()) <= SISConstants.MAX_LOAN_AMT)` – Kuldeep Parihar Dec 17 '15 at 6:20
• Why don't you want to use a try/catch block? It seems logical to me. – Nick Cook Dec 17 '15 at 6:22

IsNumeric() method works for only Integer value not for decimal value

like this

``````String str = '10';
system.debug('===strToDec=='+str.isNumeric());
``````

This will return true.

``````String str = '10.25';

Decimal strToDec = decimal.valueOf(str);

system.debug('===strToDec=='+strToDec);

String decToStr = String.valueOf(strToDec);

system.debug('===decToStr=='+decToStr);
``````

Run this code in developer console ad check output.

In you case do something like. First convert string to numeric then check and again convert string into decimal for future use

``````String  str = '10.25';
Integer intCheck = Integer.ValueOf(str);
Decimal decVal = Decimal.ValueOf(str);
if(String.ValueOf(intCheck ).isNumeric())
//use decVal here
``````

Don't understand why you need this.

• Your first solution wont work for Decimal value and i already mentioned value can be string also so it will throw Exception. – Kuldeep Parihar Dec 17 '15 at 15:41
• @KuldeepParihar as I mentioned `IsNumeric()` return true for Integer value and for decimal return false – Ratan Paul Dec 17 '15 at 15:59

As Nick Cook suggested, this is one of the rare cases when catching the exception is probably the cleanest approach:

``````Object o = ...
Decimal d;
try {
d = Decimal.valueOf(String.valueOf(o));
} catch (TypeException e) {
d = null;
// In a controller you might add the exception message e.g. "Invalid decimal: abc"
}
``````
• May be worth adding a null check for o ? – Brad Thomas May 18 '16 at 18:06

This works for me.:)

``````    public static Boolean isValidLoanValue(String value) {
String amtRegEx = '£{0,1}\\d{1,16}.{0,1}\\d*';
Pattern MyPattern = Pattern.compile(amtRegEx);
Matcher MyMatcher = MyPattern.matcher(value);
Boolean flag = MyMatcher.matches();
return flag;
}
``````