I wrote some code that does some simple checks for data conversion as part of my XmlToJson example code that I posted last year. It's simply a Pattern that we cache, and use it to quickly determine if a string is any sort of number. Here's the relevant code. First, we store a couple of patterns to pick out Booleans, decimals, dates, and date-times (everything else in the demo is treated as text):
static Pattern
boolPat = Pattern.compile('^(true|false)$'), decPat = Pattern.compile('^[-+]?\\d+(\\.\\d+)?$'),
datePat = Pattern.compile('^\\d{4}.\\d{2}.\\d{2}$'),
timePat = Pattern.compile('^\\d{4}.\\d{2}.\\d{2} (\\d{2}:\\d{2}:\\d{2} ([-+]\\d{2}:\\d{2})?)?$');
Then, when we want to auto-detect our data type, we use the following cascading ternary:
Object value =
// Nothing
String.isBlank(nodeText)? null:
// Try boolean
boolPat.matcher(nodeText).find()?
(Object)Boolean.valueOf(nodeText):
// Try decimals
decPat.matcher(nodeText).find()?
(Object)Decimal.valueOf(nodeText):
// Try dates
datePat.matcher(nodeText).find()?
(Object)Date.valueOf(nodeText):
// Try times
timePat.matcher(nodeText).find()?
(Object)DateTime.valueOf(nodeText):
// Give up, use plain text
(Object)nodeText;
You'll note that this code is try-catch free--it runs in just a few milliseconds in any scenario, which is deal for processing large amounts of values.
So, to make this work for you, you'd do this:
static Pattern decimalPattern = Pattern.compile('^[-+]?\\d+(\\.\\d*)?$');
public static Decimal getNumber(String value) {
return String.isBlank(value) || !decimalPattern.matcher(value).find()?
null: Decimal.valueOf(value);
}