X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=blobdiff_plain;f=bundles%2Forg.simantics.spreadsheet%2Fsrc%2Forg%2Fsimantics%2Fspreadsheet%2Fsolver%2Fformula%2FAverageFormulaFunction.java;fp=bundles%2Forg.simantics.spreadsheet%2Fsrc%2Forg%2Fsimantics%2Fspreadsheet%2Fsolver%2Fformula%2FAverageFormulaFunction.java;h=05528e27c2703adae2420ca996b72cb4b2501116;hb=c07a3818f0024e932a27eb85cbfd3f2291475a65;hp=0000000000000000000000000000000000000000;hpb=6c99e980d250fb9201aba93be7dcb1f55564dccd;p=simantics%2Fplatform.git diff --git a/bundles/org.simantics.spreadsheet/src/org/simantics/spreadsheet/solver/formula/AverageFormulaFunction.java b/bundles/org.simantics.spreadsheet/src/org/simantics/spreadsheet/solver/formula/AverageFormulaFunction.java new file mode 100644 index 000000000..05528e27c --- /dev/null +++ b/bundles/org.simantics.spreadsheet/src/org/simantics/spreadsheet/solver/formula/AverageFormulaFunction.java @@ -0,0 +1,51 @@ +package org.simantics.spreadsheet.solver.formula; + +import org.simantics.databoard.binding.mutable.Variant; +import org.simantics.spreadsheet.SpreadsheetMatrix; +import org.simantics.spreadsheet.Spreadsheets; +import org.simantics.spreadsheet.solver.formula.parser.ast.AstArgList; +import org.simantics.spreadsheet.solver.formula.parser.ast.AstValue; + +public class AverageFormulaFunction implements CellFormulaFunction { + + @Override + public Object evaluate(CellValueVisitor visitor, AstArgList args) { + if (args.values.size() == 0) + throw new IllegalStateException(); + Double sum = 0.0; + double count = 0.0; + for(AstValue value : args.values){ + Object res = value.accept(visitor); + if (res instanceof SpreadsheetMatrix) { + Object value2 = ((SpreadsheetMatrix) res).sumWithFormulaError(); + if(value2 instanceof String) return value2; + + sum += ((Number)value2).doubleValue(); + count += ((SpreadsheetMatrix) res).countOfActualDoubleValues(); + } else { + FormulaError2 err = FormulaError2.forObject(res); + if(err!=null) return err.getString(); + + if(res instanceof Variant){ + Double dVal = Spreadsheets.asDoubleWhereEmptyStringIsZero(res); + if(dVal==null) res = ((Variant)res).toString(); + else res = dVal; + } + + Double v = null; + if(res instanceof String && !res.equals("")){ + v = Spreadsheets.asDoubleWhereEmptyStringIsZero(res); + } + else if(res instanceof Number) + v = Spreadsheets.asDoubleWhereEmptyStringIsZero(res); + + if(v!=null){ + sum += v; + count++; + } + } + } + if(count==0.0) return FormulaError2.DIV0.getString(); + return sum/count; + } +} \ No newline at end of file