f7
f7 is a spreadsheet formula execution library
git clone https://git.vogt.world/f7.git
Log | Files | README.md | LICENSE.md
← All files
name: src/main/java/io/protobase/f7/formulas/math/ROUND.java
-rw-r--r--
1469
 1package io.protobase.f7.formulas.math;
 2
 3import io.protobase.f7.formulas.AbstractFormula;
 4import io.protobase.f7.formulas.FormulaName;
 5import io.protobase.f7.models.GridColumnRowKey;
 6import io.protobase.f7.utils.Converters;
 7
 8import java.math.BigDecimal;
 9import java.math.RoundingMode;
10import java.util.function.BiFunction;
11import java.util.function.Function;
12
13public class ROUND extends AbstractFormula {
14  public static FormulaName NAME = FormulaName.ROUND;
15  public static ROUND SELF = new ROUND();
16
17  public ROUND() {
18    super();
19  }
20
21  public ROUND(Function<Object, Object> lookup, BiFunction<GridColumnRowKey, Object, Object> collateralLookup) {
22    super(lookup, collateralLookup);
23  }
24
25  @Override
26  public Object internal(GridColumnRowKey origin, Object... values) {
27    checkLengthBetween(values.length, 1, 2, NAME);
28    Object value = Converters.first(collateralLookup.apply(origin, values[0]));
29    if (values.length == 1) {
30      return ((double) Math.round(Converters.toDouble(value)));
31    }
32    Double placesRaw = Converters.toDouble(Converters.first(collateralLookup.apply(origin, values[1])));
33    int places;
34    if (placesRaw > 0) {
35      places = new Double(Math.floor(placesRaw.floatValue())).intValue();
36    } else {
37      places = new Double(Math.ceil(placesRaw.floatValue())).intValue();
38    }
39    BigDecimal bd = new BigDecimal(Converters.toDouble(value));
40    bd = bd.setScale(places, RoundingMode.HALF_UP);
41    return bd.doubleValue();
42  }
43}