예제 #1
0
int qore_number_private::roundUp(QoreString& str, qore_offset_t pos) {
   for (; pos >= 0; --pos) {
      char c = str[pos];
      if (c == '.')
         continue;
      if (!pos && c == '-')
         break;
      if (c < '9') {
         str.replaceChar(pos, c + 1);
         break;
      }
      str.replaceChar(pos, '0');
   }
   if (pos == -1 || (!pos && str[0] == '-')) {
      str.insertch('1', pos + 1, 1);
      return 1;
   }
   return 0;
}
예제 #2
0
void qore_number_private::getAsString(QoreString& str, bool round) const {
   // first check for zero
   if (zero()) {
      str.concat("0");
      return;
   }

   mpfr_exp_t exp;

   char* buf = mpfr_get_str(0, &exp, 10, 0, num, QORE_MPFR_RND);
   if (!buf) {
      numError(str);
      return;
   }
   ON_BLOCK_EXIT(mpfr_free_str, buf);

   //printd(5, "qore_number_private::getAsString(round: %d) this: %p buf: '%s'\n", round, this, buf);

   // if it's a regular number, then format accordingly
   if (number()) {
      int sgn = sign();
      qore_size_t len = str.size() + (sgn < 0 ? 1 : 0);
      //printd(5, "qore_number_private::getAsString() this: %p '%s' exp "QLLD" len: "QLLD"\n", this, buf, exp, len);

      qore_size_t dp = 0;

      str.concat(buf);
      // trim the trailing zeros off the end
      str.trim_trailing('0');
      if (exp <= 0) {
	 exp = -exp;
	 str.insert("0.", len);
	 dp = len + 1;
	 //printd(5, "qore_number_private::getAsString() this: %p str: '%s' exp: "QLLD" dp: "QLLD" len: "QLLD"\n", this, str.getBuffer(), exp, dp, len);
	 if (exp)
	    str.insertch('0', len + 2, exp);
      }
      else {
	 // get remaining length of string (how many characters were added)
	 qore_size_t rlen = str.size() - len;

	 //printd(5, "qore_number_private::getAsString() this: %p str: '%s' exp: "QLLD" rlen: "QLLD"\n", this, str.getBuffer(), exp, rlen);

	 // assert that we have added at least 1 character
	 assert(rlen > 0);
	 if ((qore_size_t)exp > rlen)
	    str.insertch('0', str.size(), exp - rlen);
	 else if ((qore_size_t)exp < rlen) {
	    str.insertch('.', len + exp, 1);
	    dp = len + exp;
	 }
      }
      // try to do some rounding (noise reduction with binary->decimal conversions)
      if (dp && round)
         applyRoundingHeuristic(str, dp, str.size());
   }
   else
      str.concat(buf);

   //printd(5, "qore_number_private::getAsString() this: %p returning '%s'\n", this, str.getBuffer());
}