Logo Search packages:      
Sourcecode: osb-jscore version File versions  Download package

double KJS::UString::toDouble ( bool  tolerateTrailingJunk,
bool  tolerateEmptyString 
) const

Attempts an conversion to a number. Apart from floating point numbers, the algorithm will recognize hexadecimal representations (as indicated by a 0x or 0X prefix) and +/- Infinity. Returns NaN if the conversion failed.

Parameters:
tolerateTrailingJunk if true, toDouble can tolerate garbage after the number.
tolerateEmptyString if false, toDouble will turn an empty string into NaN rather than 0.

Definition at line 819 of file ustring.cpp.

References ascii(), and is8Bit().

Referenced by toULong().

{
  double d;

  // FIXME: If tolerateTrailingJunk is true, then we want to tolerate non-8-bit junk
  // after the number, so is8Bit is too strict a check.
  if (!is8Bit())
    return NaN;

  const char *c = ascii();

  // skip leading white space
  while (isspace(*c))
    c++;

  // empty string ?
  if (*c == '\0')
    return tolerateEmptyString ? 0.0 : NaN;

  // hex number ?
  if (*c == '0' && (*(c+1) == 'x' || *(c+1) == 'X')) {
    c++;
    d = 0.0;
    while (*(++c)) {
      if (*c >= '0' && *c <= '9')
      d = d * 16.0 + *c - '0';
      else if ((*c >= 'A' && *c <= 'F') || (*c >= 'a' && *c <= 'f'))
      d = d * 16.0 + (*c & 0xdf) - 'A' + 10.0;
      else
      break;
    }
  } else {
    // regular number ?
    char *end;
    d = kjs_strtod(c, &end);
    if ((d != 0.0 || end != c) && d != HUGE_VAL && d != -HUGE_VAL) {
      c = end;
    } else {
      // infinity ?
      d = 1.0;
      if (*c == '+')
      c++;
      else if (*c == '-') {
      d = -1.0;
      c++;
      }
      if (strncmp(c, "Infinity", 8) != 0)
      return NaN;
      d = d * Inf;
      c += 8;
    }
  }

  // allow trailing white space
  while (isspace(*c))
    c++;
  // don't allow anything after - unless tolerant=true
  if (!tolerateTrailingJunk && *c != '\0')
    d = NaN;

  return d;
}


Generated by  Doxygen 1.6.0   Back to index