|
1 | 1 | package com.scriptbasic.utility.functions; |
2 | 2 |
|
| 3 | +import java.math.BigDecimal; |
| 4 | +import java.math.MathContext; |
| 5 | +import java.math.RoundingMode; |
| 6 | + |
3 | 7 | import com.scriptbasic.api.BasicFunction; |
4 | 8 | import com.scriptbasic.api.ScriptBasicException; |
5 | 9 | import com.scriptbasic.interfaces.BasicRuntimeException; |
|
21 | 25 | @SuppressWarnings({"SameReturnValue", "UnusedReturnValue"}) |
22 | 26 | public class MathFunctions { |
23 | 27 |
|
| 28 | + /** |
| 29 | + * Rounding mode used by round function |
| 30 | + */ |
| 31 | + static public RoundingMode roundingMode = RoundingMode.HALF_EVEN; |
| 32 | + |
24 | 33 | private MathFunctions() { |
25 | 34 | NoInstance.isPossible(); |
26 | 35 | } |
@@ -216,9 +225,28 @@ public static double rint(final double a) { |
216 | 225 | return 0.0; |
217 | 226 | } |
218 | 227 |
|
219 | | - @BasicFunction(substituteClass = java.lang.Math.class, classification = com.scriptbasic.classification.Math.class) |
220 | | - static public double round(final double x) { |
221 | | - return 0.0; |
| 228 | + /** |
| 229 | + * Returns a number rounded to a specified number of decimal places. |
| 230 | + * |
| 231 | + * This function returns something commonly referred to as bankers rounding. |
| 232 | + * So be careful before using this function. Same behavior has 'round' in VBA. |
| 233 | + * |
| 234 | + * @param value Numeric value being rounded |
| 235 | + * @param numdecimalplaces Number indicating how many places to the right of the decimal |
| 236 | + * are included in the rounding. |
| 237 | + * @return rounded value |
| 238 | + */ |
| 239 | + @BasicFunction(classification = com.scriptbasic.classification.Math.class) |
| 240 | + static public Number round(final double value, Integer numdecimalplaces) { |
| 241 | + |
| 242 | + final BigDecimal bd = BigDecimal.valueOf(value); |
| 243 | + |
| 244 | + if (numdecimalplaces == null || numdecimalplaces == 0) { |
| 245 | + return bd.setScale(0, roundingMode).intValue(); |
| 246 | + } else { |
| 247 | + final MathContext mc = new MathContext(numdecimalplaces, roundingMode); |
| 248 | + return bd.round(mc).doubleValue(); |
| 249 | + } |
222 | 250 | } |
223 | 251 |
|
224 | 252 | @BasicFunction(substituteClass = java.lang.Math.class, classification = com.scriptbasic.classification.Math.class) |
|
0 commit comments