Skip to content

Instantly share code, notes, and snippets.

@h4ck4life
Created June 11, 2018 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h4ck4life/f46355826e889ebd34d6896fbb91f717 to your computer and use it in GitHub Desktop.
Save h4ck4life/f46355826e889ebd34d6896fbb91f717 to your computer and use it in GitHub Desktop.
Rounding to the nearest 5 cents
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Arrays;
public class RoundDemo {
public static void main(String[] args) {
for (int n : Arrays.asList(
8201,
8202,
8203,
8204,
8205,
8206,
8207,
8208,
8209)) {
System.out.println(n + " --> " + round(n));
}
}
public static int roundUp(int value) {
BigDecimal bg = BigDecimal.valueOf(value).movePointLeft(2);
bg = bg.setScale(1, RoundingMode.HALF_UP);
String rounded = new DecimalFormat("0.00").format(bg);
return (Integer.parseInt(rounded.replace(".", "")));
}
public static int round(int amount){
BigDecimal bg = BigDecimal.valueOf(amount).movePointLeft(2);
Double rounded = ((double) (long) (bg.doubleValue() * 20 + 0.5)) / 20;
String roundedStr = new DecimalFormat("0.00").format(rounded);
return Integer.parseInt(roundedStr.replace(".", ""));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment