QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
    // Note: not using straight sprintf here because we do NOT want
    // localized number formatting.
    if(!valid(unit))
        return QString(); // Refuse to format invalid unit
    qint64 n = (qint64)nIn;
    qint64 coin = factor(unit);
    int num_decimals = decimals(unit);
    qint64 n_abs = (n > 0 ? n : -n);
    qint64 quotient = n_abs / coin;
    qint64 remainder = n_abs % coin;
    QString quotient_str = QString::number(quotient);
    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');


    /*Right-trim excess zeros after the decimal point*/
    int nTrim = 0;
    for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
        ++nTrim;
    remainder_str.chop(nTrim);

    // Use SI-style thin space separators as these are locale independent and can't be
    // confused with the decimal marker.
    QChar thin_sp(THIN_SP_CP);
    int q_size = quotient_str.size();
    if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
        for (int i = 3; i < q_size; i += 3)
            quotient_str.insert(q_size - i, thin_sp);

    if (n < 0)
        quotient_str.insert(0, '-');
    else if (fPlus && n > 0)
        quotient_str.insert(0, '+');
    return quotient_str + QString(".") + remainder_str;
}
Exemple #2
0
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
    if(!valid(unit) || value.isEmpty())
        return false; // Refuse to parse invalid unit or empty string
    int num_decimals = decimals(unit);
    QStringList parts = value.split(".");

    if(parts.size() > 2)
    {
        return false; // More than one dot
    }
    QString whole = parts[0];
    QString decimals;

    if(parts.size() > 1)
    {
        decimals = parts[1];
    }
    if(decimals.size() > num_decimals)
    {
        return false; // Exceeds max precision
    }
    bool ok = false;
    QString str = whole + decimals.leftJustified(num_decimals, '0');

    if(str.size() > 18)
    {
        return false; // Longer numbers will exceed 63 bits
    }
    qint64 retvalue = str.toLongLong(&ok);
    if(val_out)
    {
        *val_out = retvalue;
    }
    return ok;
}
Exemple #3
0
int ValueSlider::
        decimals(qreal r) const
{
    int d = decimals();

    r = fabs(r);

    if (r>0)
    {
        while(r<0.099)
        {
            r*=10;
            d++;
        }
        while(r>=1.1 && d>0)
        {
            r/=10;
            d--;
        }
    }

    return d;

}
Exemple #4
0
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
    if(!valid(unit) || value.isEmpty())

    int num_decimals = decimals(unit);
    QStringList parts = value.split(".");

    if(parts.size() > 2)
    {

    }
    QString whole = parts[0];
    QString decimals;

    if(parts.size() > 1)
    {
        decimals = parts[1];
    }
    if(decimals.size() > num_decimals)
    {

    }
    bool ok = false;
    QString str = whole + decimals.leftJustified(num_decimals, '0');

    if(str.size() > 18)
    {

    }
    qint64 retvalue = str.toLongLong(&ok);
    if(val_out)
    {
        *val_out = retvalue;
    }
    return ok;
}
Exemple #5
0
bool Format::parse( const String &fmt )
{

   String tmp;
   uint32 pos = 0;
   uint32 len = fmt.length();

   typedef enum {
      e_sInitial,
      e_sSize,
      e_sDecimals,
      e_sPadding,
      e_sDecSep,
      e_sGroupSep,
      e_sGroupSep2,
      e_sErrorEffect,
      e_sErrorEffect2,
      e_sNilMode,
      e_sNegFmt,
      e_sNegFmt2
   }
   t_state;
   t_state state = e_sInitial;


   while( pos < len )
   {
      uint32 chr = fmt.getCharAt( pos );

      switch( state )
      {

         //=============================
         // Basic state.
         //
         case e_sInitial:
            if( chr >= '0' && chr <= '9' )
            {
               // size already given
               if ( m_size != 0 )
                  return false;

               state = e_sSize;
               tmp.size(0);
               tmp += chr;
               break;
            }

            // else:
            switch( chr )
            {
               case 'N':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_decimal );
               break;

               case '.':
                  // it should be an octal.
                  m_convType = e_tNum;
                  state = e_sDecimals;
                  tmp.size(0);
               break;

               case 'b':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_binary );
               break;

               case 'B':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_binaryB );
               break;

               case 'd':
                  m_convType = e_tNum;
                  state = e_sDecSep;
               break;

               case 'p':
                  state = e_sPadding;
               break;

               case 'g':
                  m_convType = e_tNum;
                  state = e_sGroupSep;
               break;

               case 'G':
                  m_convType = e_tNum;
                  state = e_sGroupSep2;
               break;

               case '0':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_octalZero );
               break;

               case 'o':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_octal );
               break;

               case 'x':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_hexLower );
               break;

               case 'X':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_hexUpper );
               break;

               case 'c':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_cHexLower );
               break;

               case 'C':
                  // it should be an octal.
                  m_convType = e_tNum;
                  numFormat( e_cHexUpper );
               break;

               case 'e':
                  // it should be in scientific format
                  m_convType = e_tNum;
                  numFormat( e_scientific );
               break;

               case '/':
                  // it should be an octal.
                  state = e_sErrorEffect;
               break;

               case 'n':
                  state = e_sNilMode;
               break;

               case '|':
                  m_posOfObjectFmt = pos;
                  m_convType = e_tStr;
                  // complete parsing
                  pos = len;
               break;

               case '+':
                  m_negFormat = e_plusMinusFront;
                  state = e_sNegFmt;
               break;

               case '-':
                  m_negFormat = e_minusFront;
                  state = e_sNegFmt2;
               break;

               case '[':
                  m_negFormat = e_parenthesis;
               break;

               case ']':
                  m_negFormat = e_parpad;
               break;

               case 'r':
                  m_rightAlign = true;
               break;

               default:
                  // unrecognized character
                  m_convType = e_tError;
                  return false;
            }
         break;

         //=============================
         // Parse padding
         //
         case e_sDecSep:
            m_decimalSep = chr;
            state = e_sInitial;
         break;

         case e_sPadding:
            m_paddingChr = chr;
            state = e_sInitial;
         break;

         case e_sGroupSep:
            if( chr >= '0' && chr <='9' )
            {
               m_grouping = chr - '0';
               state = e_sGroupSep2;
            }
            else {
               m_thousandSep = chr;
               state = e_sInitial;
            }
         break;

         case e_sGroupSep2:
            m_thousandSep = chr;
            state = e_sInitial;
         break;

         //=============================
         // Size parsing state
         //
         case e_sSize:
            if( chr >= '0' && chr <= '9' )
            {
               tmp += chr;

               // size too wide
               if ( tmp.length() > 4 ) {
                  m_convType = e_tError;
                  return false;
               }
            }
            else
            {
               int64 tgt;
               tmp.parseInt( tgt );
               fieldSize( (uint16) tgt );

               if( chr == '*' )
               {
                  fixedSize( true );
               }
               else {
                  // reparse current char
                  --pos;
               }

               state = e_sInitial;
            }
         break;

         //=============================
         // Decimals parsing state
         //
         case e_sDecimals:
            if( chr >= '0' && chr <= '9' )
            {
               tmp += chr;

               // size too wide
               if ( tmp.length() > 2 ) {
                  m_convType = e_tError;
                  return false;
               }
            }
            else
            {
               int64 tgt;
               tmp.parseInt( tgt );
               decimals( (uint8) tgt );
               // reparse current char
               --pos;
               state = e_sInitial;
            }
         break;

         //===============================================
         // Parsing what should be done in case of error.
         //
         case e_sErrorEffect:
            if ( chr == 'c' )
            {
               state = e_sErrorEffect2;
               break;
            }

            // else
            switch( chr )
            {
               case 'n': mismatchAction( e_actNil ); break;
               case '0': mismatchAction( e_actZero ); break;
               case 'r': mismatchAction( e_actRaise ); break;

               default:
                  // invalid choiche
                  m_convType = e_tError;
                  return false;
            }

            state = e_sInitial;
         break;

         case e_sErrorEffect2:
            switch( chr )
            {
               case 'n': mismatchAction( e_actConvertNil ); break;
               case '0': mismatchAction( e_actConvertZero ); break;
               case 'r': mismatchAction( e_actConvertRaise ); break;

               default:
                  // invalid choiche
                  m_convType = e_tError;
                  return false;
            }
            state = e_sInitial;
         break;

         //=================================
         // parsing what do to with a Nil
         //
         case e_sNilMode:
            switch( chr )
            {
               case 'n': m_nilFormat = e_nilEmpty; break;
               case 'N': m_nilFormat = e_nilN; break;
               case 'l': m_nilFormat = e_nilnil; break;
               case 'L': m_nilFormat = e_nilNil; break;
               case 'u': m_nilFormat = e_nilNull; break;
               case 'U': m_nilFormat = e_nilNULL; break;
               case 'o': m_nilFormat = e_nilNone; break;
               case 'A': m_nilFormat = e_nilNA; break;

               default:
                  m_convType = e_tError;
                  return false;
            }
            state = e_sInitial;
         break;

         //=================================
         // Parsing neg format
         case e_sNegFmt:
            switch( chr ) {
               case '+': m_negFormat = e_plusMinusBack; break;
               case '^': m_negFormat = e_plusMinusEnd; break;
               default:
                  pos--;
            }
            state = e_sInitial;
         break;

         //=================================
         // Parsing neg format 2
         case e_sNegFmt2:
            switch( chr ) {
               case '-': m_negFormat = e_minusBack; break;
               case '^': m_negFormat = e_minusEnd; break;
               default:
                  pos--;
            }
            state = e_sInitial;
         break;

      }

      ++pos;
   } // end main loop


   // verify output status
   switch( state )
   {
      case e_sInitial: // ok
      case e_sNegFmt:
      break;

      case e_sSize:
      {
         int64 tgt;
         tmp.parseInt( tgt );
         fieldSize( (uint8) tgt );
      }
      break;

      case e_sDecimals:
      {
         int64 tgt;
         tmp.parseInt( tgt );
         decimals( (uint8) tgt );
      }
      break;

      // any other state means we're left in the middle of something
      default:
         m_convType = e_tError;
         return false;
   }

   // if everything goes fine...
   m_originalFormat = fmt;
   return true;
}
 QString textFromValue(double value) const
 {
     return QLocale().toString(value, 'f', decimals());
 }
Exemple #7
0
QString ValueSlider::
        valueAsString(bool forceDisableUnits) const
{
    return QString("%1%2").arg(value_,0,'f',decimals(value_)).arg (unit_.isEmpty () || hasFocus () || forceDisableUnits?"":" " + unit_);
}
bool BitcoinUnits::parse(int unit, const QString &value, int nColorIn, qint64 *val_out)
{
    if(!valid(unit, nColorIn) || value.isEmpty())
        return false; // Refuse to parse invalid unit or empty string
    int num_decimals = decimals(unit, nColorIn);
    QStringList parts = value.split(".");

    if(parts.size() > 2)
    {
        if (fDebug)
        {
              printf("BitcoinUnits::parse: More than one dot!\n");
        }
        return false; // More than one dot
    }
    QString whole = parts[0];
    QString decimals;

    if(parts.size() > 1)
    {
        bool fNonzero = false;
        for (int i = 0; i < parts[1].size(); ++i)
        {
            if (parts[1][i] != '0')
            {
                fNonzero = true;
                break;
            }
        }
        if (fNonzero)
        {
            decimals = parts[1];
        }
    }

    if(decimals.size() > num_decimals)
    {
        if (fDebug)
        {
              printf("BitcoinUnits::parse: Size %d exceeds # decimals %d\n",
                              decimals.size(), num_decimals);
        }
        return false; // Exceeds max precision
    }
    bool ok = false;
    QString str = whole + decimals.leftJustified(num_decimals, '0');
    if (!ok)
    {
        if (fDebug)
        {
              printf("BitcoinUnits::parse: Couldn't left justify '%s'\n",
                              str.toUtf8().constData());
        }
    }

    if(str.size() > 18)
    {
        if (fDebug)
        {
              printf("BitcoinUnits::parse: String size (%d) too big\n",
                              str.size());
        }
        return false; // Longer numbers will exceed 63 bits
    }
    qint64 retvalue = str.toLongLong(&ok);
    if (!ok)
    {
        if (fDebug)
        {
              printf("BitcoinUnits::parse: Couldn't convert to LL '%s'\n",
                              str.toUtf8().constData());
        }
    }

    if(val_out)
    {
        *val_out = retvalue;
    }
    return ok;
}
Exemple #9
0
void QDoubleValidator::setTop(double top)
{
    setRange(bottom(), top, decimals());
}
Exemple #10
0
RcppExport SEXP xbrlProcessFacts(SEXP epaDoc) {
  xmlDocPtr doc = (xmlDocPtr) R_ExternalPtrAddr(epaDoc);

  xmlXPathContextPtr context = xmlXPathNewContext(doc);
  xmlXPathObjectPtr fact_res = xmlXPathEvalExpression((xmlChar*) "//*[@*[local-name()='contextRef']]", context);
  xmlNodeSetPtr fact_nodeset = fact_res->nodesetval;
  xmlXPathFreeContext(context);

  int fact_nodeset_ln = fact_nodeset->nodeNr;

  CharacterVector elementId(fact_nodeset_ln);
  CharacterVector contextId(fact_nodeset_ln);
  CharacterVector unitId(fact_nodeset_ln);
  CharacterVector fact(fact_nodeset_ln);
  CharacterVector decimals(fact_nodeset_ln);
  CharacterVector sign(fact_nodeset_ln);
  CharacterVector scale(fact_nodeset_ln);
  CharacterVector tupleRef(fact_nodeset_ln);
  CharacterVector order(fact_nodeset_ln);
  CharacterVector factId(fact_nodeset_ln);
  CharacterVector ns(fact_nodeset_ln);

  for (int i=0; i < fact_nodeset_ln; i++) {
    xmlNodePtr fact_node = fact_nodeset->nodeTab[i];

    if (fact_node->ns->prefix)
      elementId[i] = (char *) ((string) (char *) fact_node->ns->prefix + "_" + (string) (char *) fact_node->name).data();
    else
      elementId[i] = (char *) fact_node->name;

    xmlChar *tmp_str;
    if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "contextRef"))) { 
      contextId[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      contextId[i] = NA_STRING;
    }
    if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "unitRef"))) { 
      unitId[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      unitId[i] = NA_STRING;
    }
    if ((tmp_str = xmlNodeListGetString(doc, fact_node->xmlChildrenNode, 1))) {
      fact[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      fact[i] = NA_STRING;
    }
    if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "decimals"))) { 
      decimals[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      decimals[i] = NA_STRING;
    }
    if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "scale"))) { 
      scale[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      scale[i] = NA_STRING;
    }
    if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "sign"))) { 
      sign[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      sign[i] = NA_STRING;
    }
    if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "tupleRef"))) { 
      sign[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      sign[i] = NA_STRING;
    }
    if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "order"))) { 
      sign[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      sign[i] = NA_STRING;
    }
    if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "id"))) { 
      factId[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else if ((tmp_str = xmlGetProp(fact_node, (xmlChar*) "name"))) { 
      factId[i] = (char *) tmp_str;
      xmlFree(tmp_str);
    } else {
      factId[i] = NA_STRING;
    }
    ns[i] = (char *) fact_node->ns->href;
  }
  xmlXPathFreeObject(fact_res);

  return DataFrame::create(Named("elementId")=elementId,
			   Named("contextId")=contextId,
			   Named("unitId")=unitId,
			   Named("fact")=fact,
			   Named("factId")=factId,
			   Named("decimals")=decimals,
			   Named("scale")=scale,
			   Named("sign")=sign,
			   Named("tupleRef")=tupleRef,
			   Named("order")=order,
			   Named("ns")=ns);
}
double EqonomizeValueEdit::fixup_sub(QString &input, QStringList &errors, bool &calculated) const {
	input = input.trimmed();
	if(input.isEmpty()) {
		return 0.0;
	}
	if(o_currency) {
		input.remove(budget->monetary_group_separator);
		if(!budget->monetary_negative_sign.isEmpty()) input.replace(budget->monetary_negative_sign, "-");
		if(!budget->monetary_positive_sign.isEmpty()) input.replace(budget->monetary_positive_sign, "+");
	} else {
		input.remove(budget->group_separator);
		if(!budget->negative_sign.isEmpty()) input.replace(budget->negative_sign, "-");
		if(!budget->positive_sign.isEmpty()) input.replace(budget->positive_sign, "+");
	}
	input.replace(QLocale().negativeSign(), '-');
	input.replace(QLocale().positiveSign(), '+');
	int i = input.indexOf(')', 1);
	if(i < 1) {
		i = input.indexOf('(', 0);
		if(i == 0) {
			input.remove(0, 1);
			return fixup_sub(input, errors, calculated);
		} else if(i >= 0) {
			input += ')';
			i = input.length() - 1;
		} else {
			i = -1;
		}
	}
	if(i >= 1) {
		int i2 = input.lastIndexOf('(', i - 1);
		if(i2 < 0 || i2 > i) {
			if(i == input.length() - 1) {
				input.chop(1);
				return fixup_sub(input, errors, calculated);
			}
			input.prepend('(');
			i++;
			i2 = 0;
		}
		if(i2 == 0 && i == input.length() - 1) {
			input.remove(0, 1);
			input.chop(1);
			return fixup_sub(input, errors, calculated);
		}
		if(i < input.length() - 1 && (input[i + 1].isNumber() || input[i + 1] == '(')) input.insert(i + 1, '*');
		QString str = input.mid(i2 + 1, i - i2 - 1);
		double v = fixup_sub(str, errors, calculated);
		input.replace(i2, i - i2 + 1, o_currency ? o_currency->formatValue(0.5, decimals() + 2, false, false, true) : budget->formatValue(v, decimals() + 2));
		if(i2 > 0 && (input[i2 - 1].isNumber() || input[i2 - 1] == ')')) input.insert(i2, '*');
		calculated = true;
		return fixup_sub(input, errors, calculated);
	}
	i = input.indexOf(QRegExp("[-+]"), 1);
	if(i >= 1) {
		QStringList terms = input.split(QRegExp("[-+]"));
		i = 0;
		double v = 0.0;
		QList<bool> signs;
		signs << true;
		for(int terms_i = 0; terms_i < terms.size() - 1; terms_i++) {
			i += terms[terms_i].length();
			if(input[i] == '-') signs << false;
			else signs << true;
			i++;
		}
		for(int terms_i = 0; terms_i < terms.size() - 1; terms_i++) {
			if(terms[terms_i].endsWith('*') || terms[terms_i].endsWith('/') || terms[terms_i].endsWith('^')) {
				if(!signs[terms_i + 1]) terms[terms_i] += '-';
				else terms[terms_i] += '+';
				terms[terms_i] += terms[terms_i + 1];
				signs.removeAt(terms_i + 1);
				terms.removeAt(terms_i + 1);
				terms_i--;
			}
		}
		if(terms.size() > 1) {
			for(int terms_i = 0; terms_i < terms.size(); terms_i++) {
				if(terms[terms_i].isEmpty()) {
					if(!signs[terms_i] && terms_i + 1 < terms.size()) {
						signs[terms_i + 1] = !signs[terms_i + 1];
					}
				} else {					
					if(!signs[terms_i]) v -= fixup_sub(terms[terms_i], errors, calculated);
					else v += fixup_sub(terms[terms_i], errors, calculated);
				}
			}			
			calculated = true;
			return v;
		}
	}
	if(input.indexOf("**") >= 0) input.replace("**", "^");
	i = input.indexOf(QRegExp("[*/]"), 0);
	if(i >= 0) {
		QStringList terms = input.split(QRegExp("[*/]"));
		QChar c = '*';
		i = 0;
		double v = 1.0;
		for(int terms_i = 0; terms_i < terms.size(); terms_i++) {
			if(terms[terms_i].isEmpty()) {
				if(c == '/') {
					errors << tr("Empty denominator.");
				} else {
					errors << tr("Empty factor.");
				}
			} else {
				i += terms[terms_i].length();
				if(c == '/') {
					double den = fixup_sub(terms[terms_i], errors, calculated);
					if(den == 0.0) {
						errors << tr("Division by zero.");
					} else {
						v /= den;
					}
				} else {
					v *= fixup_sub(terms[terms_i], errors, calculated);
				}
				if(i < input.length()) c = input[i];
			}
			i++;
		}
		calculated = true;
		return v;
	}
	i = input.indexOf(QLocale().percent());
	if(i >= 0) {
		double v = 0.01;
		if(input.length() > 1) {
			if(i > 0 && i < input.length() - 1) {
				QString str = input.right(input.length() - 1 - i);
				input = input.left(i);
				i = 0;
				v = fixup_sub(str, errors, calculated) * v;
			} else if(i == input.length() - 1) {
				input = input.left(i);
			} else if(i == 0) {
				input = input.right(input.length() - 1);
			}
			v = fixup_sub(input, errors, calculated) * v;
		}
		calculated = true;
		return v;
	}	
	if(o_currency) {
		QString reg_exp_str = "[\\d\\+\\-\\^";
		reg_exp_str += '\\';
		reg_exp_str += budget->monetary_decimal_separator;
		reg_exp_str += '\\';
		reg_exp_str += budget->monetary_group_separator;
		if(budget->monetary_decimal_separator != "." && budget->monetary_group_separator != ".") {
			reg_exp_str += '\\';
			reg_exp_str += '.';
		}
		reg_exp_str += "]";
		int i = input.indexOf(QRegExp(reg_exp_str));
		if(i >= 1) {
			QString scur = input.left(i).trimmed();
			Currency *cur = budget->findCurrency(scur);
			if(!cur && budget->defaultCurrency()->symbol(false) == scur) cur = budget->defaultCurrency();
			if(!cur) cur = budget->findCurrencySymbol(scur, true);
			if(cur) {
				QString value = input.right(input.length() - i);				
				double v = fixup_sub(value, errors, calculated);
				if(cur != o_currency) {
					v = cur->convertTo(v, o_currency);
				}
				calculated = true;
				return v;
			}
			errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(scur);
		}
		if(i >= 0) {
			i = input.lastIndexOf(QRegExp(reg_exp_str));
			if(i >= 0 && i < input.length() - 1) {
				QString scur = input.right(input.length() - (i + 1)).trimmed();
				Currency *cur = budget->findCurrency(scur);
				if(!cur && budget->defaultCurrency()->symbol(false) == scur) cur = budget->defaultCurrency();
				if(!cur) cur = budget->findCurrencySymbol(scur, true);
				if(cur) {
					QString value = input.left(i + 1);
					double v = fixup_sub(value, errors, calculated);
					if(cur != o_currency) {
						v = cur->convertTo(v, o_currency);
					}
					calculated = true;
					return v;
				}
				errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(scur);
			}
		} else {
			Currency *cur = budget->findCurrency(input);
			if(!cur && budget->defaultCurrency()->symbol(false) == input) cur = budget->defaultCurrency();
			if(!cur) cur = budget->findCurrencySymbol(input, true);
			if(cur) {
				double v = 1.0;
				if(cur != o_currency) {
					v = cur->convertTo(v, o_currency);
				}
				calculated = true;
				return v;
			}
			errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(input);
		}
	}
	i = input.indexOf('^', 0);
	if(i >= 0 && i != input.length() - 1) {
		QString base = input.left(i);
		if(base.isEmpty()) {
			errors << tr("Empty base.");
		} else {
			QString exp = input.right(input.length() - (i + 1));
			double v;
			if(exp.isEmpty()) {
				errors << tr("Error"), tr("Empty exponent.");
				v = 1.0;
			} else {
				v = pow(fixup_sub(base, errors, calculated), fixup_sub(exp, errors, calculated));
			}
			calculated = true;
			return v;
		}
	}
	
	if(!o_currency) {
		QString reg_exp_str = "[^\\d\\+\\-";
		reg_exp_str += '\\';
		reg_exp_str += budget->decimal_separator;
		reg_exp_str += '\\';
		reg_exp_str += budget->group_separator;
		if(budget->decimal_separator != "." && budget->group_separator != ".") {
			reg_exp_str += '\\';
			reg_exp_str += '.';
		}
		reg_exp_str += "]";
		i = input.indexOf(QRegExp(reg_exp_str));
		if(i >= 0) {
			errors << tr("Unrecognized characters in expression.");
		}
		input.remove(budget->group_separator);
		input.replace(budget->decimal_separator, ".");
		return input.toDouble();
	}
	input.remove(budget->monetary_group_separator);
	input.replace(budget->monetary_decimal_separator, ".");
	return input.toDouble();
}
QString EqonomizeValueEdit::textFromValue(double value) const {
	if(o_currency) return o_currency->formatValue(value, decimals(), true, false, true);
	if(!s_suffix.isEmpty()) return s_prefix + budget->formatValue(value, decimals()) + QString(" ") + s_suffix;
	return s_prefix + budget->formatValue(value, decimals());
}
Exemple #13
0
void BigNumDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    bool selected = option.state & QStyle::State_Selected;
    bool mouseOver = option.state & QStyle::State_MouseOver;
    QPalette palette(option.palette);
    if (selected){
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.highlight());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.highlightedText());
    }
    else if (mouseOver) {
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.button());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.buttonText());
    }
    else{
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.base());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.text());
    }
    QRect labelRect(option.rect.x(), option.rect.y(), option.rect.width(), option.rect.height());
    if (m_adjustPadding)
        labelRect.adjust(LabelPadding, LabelPadding, -(2 * LabelPadding), -(2 * LabelPadding));
    m_label->setPalette(palette);
    m_label->setFixedSize(qMax(0, labelRect.width()), labelRect.height());
    if (index.model()->data(index, Qt::DisplayRole).isNull()) {
        m_label->clear();
    }
    else {
        m_label->setText(
            (index.model()->data(index, CustomStyleRole).toString().contains("%1") ? index.model()->data(index, CustomStyleRole).toString() : QString("%1"))
            .arg(prefix() + m_label->locale().toString(index.model()->data(index, Qt::DisplayRole).toDouble(), 'f', decimals()) + suffix())
        );
    }
    if (index.model()->data(index, Qt::TextAlignmentRole).isNull())
        m_label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    else
        m_label->setAlignment(Qt::Alignment(index.model()->data(index, Qt::TextAlignmentRole).toInt()));
    QPixmap pixmap(m_label->size());
    m_label->render(&pixmap);
    painter->drawPixmap(labelRect, pixmap);
}
/** Validate a string against current constraint */
bool TextFieldBody::validate(const QString &s, int line, int col) {
    bool ok = false;

    switch ((MidpConstraint)(constraints & MIDP_CONSTRAINT_MASK)) {
    case MIDP_CONSTRAINT_NUMERIC:
      {
	QRegExp numbers("^-?[0-9]*$");
	if (numbers.match(s) >= 0) {
	  if (length() == 0) {
	    ok = true;
	  } else if (s[0] == '-') {  /* only allow one '-' & at beginning */
	    if (text()[0] != '-' && line == 0 && col == 0) {
	      ok = true;
	    }
	  } else {  /* number(s) being entered */
	    if (text()[0] != '-') {  /* positive integer */
	      ok = true;
	    } else {  /* negative integer-allow digits only after '-' */
	      if (col > 0 || line > 0) {
		ok = true;
	      }
	    }
	  }
	}
      }
      break;
    case MIDP_CONSTRAINT_DECIMAL:
	{
	  QRegExp decimals("^-?[0-9]*[.]?[0-9]*$");
	  if (decimals.match(s) >= 0) {
	    if (length() == 0) {
	      ok = true;
	    } else {
	      if (s[0] == '-') {  /* only allow one '-' & at beginning */
		if (text()[0] != '-' && line == 0 && col == 0) {
		  ok = true;
		}
	      } else {     /* number(s) being entered */
		if (text()[0] != '-') {    /* positive decimal */
		  ok = true;
		} else {  /* negative decimal-allow digits only after '-' */
		  if (col > 0 || line > 0) {
		    ok = true;
		  }
		}
	      }
	      /* Only allow one dot(.) */
	      if (ok) {
		if (s.find('.') >= 0 && text().find('.') >= 0) {
		  ok = false;
		}
	      }
	    }
	  }
	}
	break;
    case MIDP_CONSTRAINT_PHONENUMBER:
    {
        /* the phone number has to accept the '+' at the start of the text, any digits, '#' and '*' */
        QRegExp numbers("^[\053]?[0-9\\s\052\043]*$");
        if (numbers.match(s) >= 0) {
            ok = true;
        }
    }
    break;
    case MIDP_CONSTRAINT_ANY:
    case MIDP_CONSTRAINT_EMAILADDR:
    case MIDP_CONSTRAINT_URL:
        ok = true;
        break;

    } /* end of switch(constraints) */
    
    return ok;
}
Exemple #15
0
/*
 * The code of the following function is taken from kdeui/knumvalidator.cpp
 * and adjusted to always use the monetary symbols defined in the KDE System Settings
 */
QValidator::State kMyMoneyMoneyValidator::validate(QString & input, int & _p) const
{
  QString s = input;
  // TODO: port this to kf5
#if 0
  KLocale * l = KLocale::global();
  // ok, we have to re-format the number to have:
  // 1. decimalSymbol == '.'
  // 2. negativeSign  == '-'
  // 3. positiveSign  == <empty>
  // 4. thousandsSeparator() == <empty> (we don't check that there
  //    are exactly three decimals between each separator):
  QString d = l->monetaryDecimalSymbol(),
              n = l->negativeSign(),
                  p = l->positiveSign(),
                      t = l->monetaryThousandsSeparator();
  // first, delete p's and t's:
  if (!p.isEmpty())
    for (int idx = s.indexOf(p) ; idx >= 0 ; idx = s.indexOf(p, idx))
      s.remove(idx, p.length());


  if (!t.isEmpty())
    for (int idx = s.indexOf(t) ; idx >= 0 ; idx = s.indexOf(t, idx))
      s.remove(idx, t.length());

  // then, replace the d's and n's
  if ((!n.isEmpty() && n.indexOf('.') != -1) ||
      (!d.isEmpty() && d.indexOf('-') != -1)) {
    // make sure we don't replace something twice:
    qWarning() << "KDoubleValidator: decimal symbol contains '-' or "
    "negative sign contains '.' -> improve algorithm" << endl;
    return Invalid;
  }

  if (!d.isEmpty() && d != ".")
    for (int idx = s.indexOf(d) ; idx >= 0 ; idx = s.indexOf(d, idx + 1))
      s.replace(idx, d.length(), ".");

  if (!n.isEmpty() && n != "-")
    for (int idx = s.indexOf(n) ; idx >= 0 ; idx = s.indexOf(n, idx + 1))
      s.replace(idx, n.length(), "-");

  // Take care of monetary parens around the value if selected via
  // the locale settings.
  // If the lead-in or lead-out paren is present, remove it
  // before passing the string to the QDoubleValidator
  if (l->negativeMonetarySignPosition() == KLocale::ParensAround
      || l->positiveMonetarySignPosition() == KLocale::ParensAround) {
    QRegExp regExp("^(\\()?([\\d-\\.]*)(\\))?$");
    if (s.indexOf(regExp) != -1) {
      s = regExp.cap(2);
    }
  }

  // check for non numeric values (QDoubleValidator allows an 'e', we don't)
  QRegExp nonNumeric("[^\\d-\\.]+");
  if (s.indexOf(nonNumeric) != -1)
    return Invalid;

  // check for minus sign trailing the number
  QRegExp trailingMinus("^([^-]*)\\w*-$");
  if (s.indexOf(trailingMinus) != -1) {
    s = QString("-%1").arg(trailingMinus.cap(1));
  }

  // check for the maximum allowed number of decimal places
  int decPos = s.indexOf('.');
  if (decPos != -1) {
    if (decimals() == 0)
      return Invalid;
    if (((int)(s.length()) - decPos) > decimals())
      return Invalid;
  }

  // If we have just a single minus sign, we are done
  if (s == QString("-"))
    return Acceptable;

  QValidator::State rc = QDoubleValidator::validate(s, _p);
  if (rc == Acceptable) {
    // If the numeric value is acceptable, we check if the parens
    // are ok. If only the lead-in is present, the return value
    // is intermediate, if only the lead-out is present then it
    // definitely is invalid. Nevertheless, we check for parens
    // only, if the locale settings have it enabled.
    if (l->negativeMonetarySignPosition() == KLocale::ParensAround
        || l->positiveMonetarySignPosition() == KLocale::ParensAround) {
      int tmp = input.count('(') - input.count(')');
      if (tmp > 0)
        rc = Intermediate;
      else if (tmp < 0)
        rc = Invalid;
    }
  }
  return rc;
#else
  return Acceptable;
#endif
}
QString DurationSpinBox::textFromValue ( double value ) const
{
    QString s = KGlobal::locale()->formatNumber( qMin( qMax( minimum(), value ), maximum() ), decimals() );
    s += Duration::unitToString( m_unit, true );
    //kDebug(planDbg())<<2<<value<<s;
    return s;
}
Exemple #17
0
void SpinBoxFP::valueChange(double)
{
	double div = exp10(decimals());
	emit valueChanged(int(value() * div));
}
Exemple #18
0
void QDoubleValidator::setBottom(double bottom)
{
    setRange(bottom, top(), decimals());
}
Exemple #19
0
void SpinBoxFP::setValue(int val)
{
	double div = exp10(decimals());
	QDoubleSpinBox::setValue(double(val) / div);
}
QString BitcoinUnits::format(int unit, qint64 n, int nColorIn,
                                           bool fPlus, bool localized)
{
    // Note: not using straight sprintf here because we do NOT want
    // localized number formatting.
    if(!valid(unit, nColorIn))
    {
        return QString(); // Refuse to format invalid unit
    }

    QLocale locale = QLocale::c();
    QString decimal(".");
    if (localized)
    {
         decimal = QString(locale.decimalPoint());
    }

    qint64 coin = factor(unit, nColorIn);
    int num_decimals = decimals(unit, nColorIn);
    qint64 n_abs = (n > 0 ? n : -n);
    qint64 quotient = n_abs / coin;
    qint64 remainder = n_abs % coin;
    QString quotient_str = QString::number(quotient);
    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');

    // Right-trim excess zeros after the decimal point
    int nTrim = 0;
    for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
        ++nTrim;
    remainder_str.chop(nTrim);

    if (localized)
    {
       QChar thousands = locale.groupSeparator();
       int N(quotient_str.size());
       for (int i = 3; i < N; ++i)
       {
           if (i % 3 == 0)
           {
               quotient_str.insert(N - i, thousands);
           }
       }
    }
    if (n < 0)
        quotient_str.insert(0, '-');
    else if (fPlus && n > 0)
        quotient_str.insert(0, '+');
    if (DECIMALS[nColorIn] == 0)
    {
        // if (remainder != 0)
        // {
        //     printf("Remainder for atomic currency is nonzero: %" PRId64, remainder);
        // }
        return quotient_str;
    }
    else
    {
        if (localized)
        {
            QChar thousandths(' ');
            int N(remainder_str.size());
            int j = 0;
            for (int i = 3; i < N; ++i)
            {
                if (i % 3 == 0)
                {
                    remainder_str.insert(i + j, thousandths);
                    ++j;
                }
            }
        }
        return quotient_str + decimal + remainder_str;
    }
}
Exemple #21
0
int SpinBoxFP::intValue()
{
	double div = exp10(decimals());
	return int(value() * div);
}
Exemple #22
0
    boost::shared_ptr<double> LCEBEvaluation::evaluate(Chromosome const & chr)const {
        int length = chr.numberOfGenes();
        boost::scoped_array<int> decimals(new int[length]);
        chr.convertGenesToDecimals(decimals.get());
        boost::shared_ptr<double> res;

        if (!isValidSequence(decimals.get()))
            return res;

        /*std::stack<double> operands;

        for(int i = 0; i < length; ++i){
            int index = decimals[i];
            int nDrawnBooklets = game.getNumberOfDrawnBooklets();

            if(index < nDrawnBooklets){
                operands.push((double)game.getDrawnBooklet(index));
            }
            else{
                if(index < nDrawnBooklets + OPERATORS.length){
                    double operand2;
                    double operand1;

                    try{
                        operand2 = operands.pop();
                    }
                    catch(EmptyStackException e){
                        return res;
                    }
                    
                    try{
                        operand1 = operands.pop();
                    }
                    catch(EmptyStackException e){
                        return res;
                    }

                    if(res == null){
                        res = 0.0;
                    }

                    switch(OPERATORS[(index-nDrawnBooklets)]){
                        case '*':
                            res = operand1 * operand2;
                            break;

                        case '/':
                            if( operand2 != 0.0f && operand1 != 0.0f &&
                                    operand1 % operand2 == 0){
                                res = operand1 / operand2;
                            }
                            else{
                                res = null;
                                return res;
                            }

                            break;

                        case '+':
                            res = operand1 + operand2;
                            break;

                        case '-':
                            res = operand1 - operand2;
                            break;

                        default:
                            break;
                    }

                    operands.push(res);
                }
            }
        }*/

        return res;
    }
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus, bool fHideAmounts)
{
    return formatMaxDecimals(unit, n, decimals(unit), fPlus, fHideAmounts);
}