public TypeValuePair evaluate(final FormulaContext context, final ParameterCallback parameters)
      throws EvaluationException {

    final int parameterCount = parameters.getParameterCount();
    if (parameterCount < 1) {
      throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_ARGUMENTS_VALUE);
    }

    final TypeRegistry typeRegistry = context.getTypeRegistry();
    final double value =
        typeRegistry.convertToNumber(parameters.getType(0), parameters.getValue(0)).doubleValue();

    if (value == 0) {
      return new TypeValuePair(TextType.TYPE, "0 ");
    }

    boolean fixedSize = false;
    int precision = 0;

    if (parameters.getParameterCount() > 1) {
      fixedSize = true;
      precision =
          typeRegistry.convertToNumber(parameters.getType(1), parameters.getValue(1)).intValue();
      if (parameters.getParameterCount() == 3) {
        final Boolean rawFixedSize =
            typeRegistry.convertToLogical(parameters.getType(2), parameters.getValue(2));
        fixedSize = rawFixedSize.booleanValue();
      }
    }

    final int log10 = computeLog10(value);

    // index will allow us to find the the index of the suffix to use
    final int index = (int) (Math.floor(log10 / 3.0) + OFFSET);
    if (index < 0 || index >= SUFFIXES.length) {
      throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_UNEXPECTED_VALUE);
    }

    // Find the adequate precision. % operator behaves badly in negative results, so we need to make
    // it work as expected
    final int roundPrecision =
        fixedSize ? (log10 - precision) : (log10 - (precision + (3 + log10 % 3) % 3));

    // Round the value
    final double roundingScale = Math.pow(10, roundPrecision);
    final double rounded = Math.round(value / roundingScale) * roundingScale;

    // Get it's eng format. Get it as string without trailing 0's
    final double outputValue = rounded / Math.pow(10, Math.floor(log10 / 3.0) * 3);
    final int outputValueDecimalPlaces = Math.max(1, computeLog10(outputValue));

    final Locale locale = context.getLocalizationContext().getLocale();
    final NumberFormat decimalFormat =
        createDecimalFormat(fixedSize, outputValueDecimalPlaces, precision, locale);
    final String result = decimalFormat.format(outputValue) + SUFFIXES[index];
    return new TypeValuePair(TextType.TYPE, result);
  }
Example #2
0
  public TypeValuePair evaluate(final FormulaContext context, final TypeValuePair value)
      throws EvaluationException {
    final TypeRegistry typeRegistry = context.getTypeRegistry();

    Boolean valBool = typeRegistry.convertToLogical(value.getType(), value.getValue());

    if (!valBool.booleanValue()) {
      return RETURN_TRUE;
    } else {
      return RETURN_FALSE;
    }
  }