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); }
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 Type type1 = parameters.getType(0); final Object value = parameters.getValue(0); final TypeRegistry typeRegistry = context.getTypeRegistry(); final Number number = typeRegistry.convertToNumber(type1, value); if (number == null) { throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE); } int intValue = number.intValue(); if (intValue < 0) { intValue *= -1; } if (intValue % 2 == 1) { return RETURN_TRUE; } return RETURN_FALSE; }