Created
February 15, 2017 00:49
-
-
Save DmitryBe/dc53eb0b655dda9aa772c028c49d873c to your computer and use it in GitHub Desktop.
Round double with required precision
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// using math.pow | |
public static double round(double value, int places) { | |
if (places < 0) throw new IllegalArgumentException(); | |
long factor = (long) Math.pow(10, places); | |
value = value * factor; | |
long tmp = Math.round(value); | |
return (double) tmp / factor; | |
} | |
// using bigdecimal | |
public static double round(double value, int places) { | |
if (places < 0) throw new IllegalArgumentException(); | |
BigDecimal bd = new BigDecimal(value); | |
bd = bd.setScale(places, RoundingMode.HALF_UP); | |
return bd.doubleValue(); | |
} | |
// from: http://stackoverflow.com/questions/2808535/round-a-double-to-2-decimal-places |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment