File tree Expand file tree Collapse file tree 1 file changed +6
-2
lines changed
src/main/java/net/marcellperger/mathexpr/util Expand file tree Collapse file tree 1 file changed +6
-2
lines changed Original file line number Diff line number Diff line change 22
33import org .jetbrains .annotations .Range ;
44
5+ import java .math .BigDecimal ;
6+ import java .math .RoundingMode ;
7+
58public class MathUtil {
69 protected MathUtil () {}
710
8- // TODO this doesn't work: roundToSigFigs(1.22222 + 0.3, 10) == 1.5222200000000001
911 public static double roundToSigFigs (double value , @ Range (from =1 , to =Integer .MAX_VALUE ) int sigFigs ) {
1012 int mostSignificantDigit = (int )Math .floor (Math .log10 (value ));
1113 int roundToDigit = mostSignificantDigit - sigFigs + 1 ;
1214 return roundToDP (value , roundToDigit );
1315 }
1416
1517 public static double roundToNearest (double value , double nearest ) {
16- return Math .round (value / nearest ) * nearest ;
18+ BigDecimal nearestD = BigDecimal .valueOf (nearest );
19+ return BigDecimal .valueOf (value ).divide (nearestD , RoundingMode .HALF_UP )
20+ .setScale (0 , RoundingMode .HALF_UP ).multiply (nearestD ).doubleValue ();
1721 }
1822 public static double roundToDP (double value , int decimalPlaces ) {
1923 return roundToNearest (value , Math .pow (10 , decimalPlaces ));
You can’t perform that action at this time.
0 commit comments