Created
June 11, 2018 08:40
-
-
Save h4ck4life/f46355826e889ebd34d6896fbb91f717 to your computer and use it in GitHub Desktop.
Rounding to the nearest 5 cents
This file contains 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
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