Replace exponential values to double in mathematical expression

553 views Asked by At

I need to check if a mathematical expression contains a exponential value and then replace the exponential value with decimal value.

Input :"10993.657030812325*8.20681165367255E-05"

Output :"10993.657030812325*0.0000820681165367255"

The complexity I am facing is to detect it inside a mathematical expression.

The regular expression that detects a regular expression i have is:

(([1-9][0-9]*\.?[0-9]*)|(\.[0-9]+))([Ee][+-]?[0-9]+)?

However that matches true for the entire expression, is there direct way to solve this or do i have to break it down and check individually.

1

There are 1 answers

5
Dmitry Bychenko On BEST ANSWER

Providing, that exponent is not too large (less than 99) you can use this code:

  String formula = "10993.657030812325*8.20681165367255E-05";
  String pattern = @"(([1-9][0-9]*\.?[0-9]*)|(\.[0-9]+))([Ee][+-]?[0-9]+)"; 

  // Let's change format of each double precision in the formula:
  String result = Regex.Replace(formula, pattern, (match) => {
    // Simple formating; may be you should use more elaborated one
    Double db = Double.Parse(match.Value, CultureInfo.InvariantCulture);
    // Now, you should format out the Double db:
    // First eliminate exponent (F99 is the maximum possible; F100 won't do) 
    String St = db.ToString("F99", CultureInfo.InvariantCulture);

    // Next eliminate trailing '0' 
    if (St.IndexOf('.') >= 0)
      St = St.TrimEnd('0');

    return St.TrimEnd('.'); 
  });

The result is "10993.6570308123*0.0000820681165367255"