Skip to content

Instantly share code, notes, and snippets.

@DmitryBe
Created February 15, 2017 00:49
Show Gist options
  • Save DmitryBe/dc53eb0b655dda9aa772c028c49d873c to your computer and use it in GitHub Desktop.
Save DmitryBe/dc53eb0b655dda9aa772c028c49d873c to your computer and use it in GitHub Desktop.
Round double with required precision
// 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