0

I want to increase value of 6.23 to 6.25 in java. Right now I am planning to convert double to string than use split and take last two decimal digits and convert them into double. than use if() condtions. Any function in java which can do this for me? Or any other way?

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
TechHelp
  • 207
  • 1
  • 5
  • 12

3 Answers3

1

If you want to do operations on currency without precision/rounding errors, you can use BigDecimal. In order to round to a whole value you must call divide() and set the scale parameter to 0...

BigDecimal precision = new BigDecimal("0.05")
BigDecimal value = new BigDecimal("6.23");
BigDecimal rounded = value.divide(precision, 0, BigDecimal.ROUND_UP).multiply(precision);
Zutty
  • 5,357
  • 26
  • 31
1
double value = 6.21;
value = value * 100;
value = Math.round((value + 2.5)/ 5.0) * 5.0;
value = value / 100;
System.out.println(value);
Stanley
  • 5,057
  • 4
  • 34
  • 44
1

You can divide by 0.05 (your precision step), round to the nearest integer, and multiply by 0.05 again:

BigDecimal precision = new BigDecimal("0.05");
BigDecimal value = new BigDecimal("6.23");
BigDecimal rounded = value.divide(precision, 0, RoundingMode.HALF_DOWN)
                          .multiply(precision);
System.out.println("rounded = " + rounded); //prints 6.25

You can then extract that in a utility method:

public class Test {

    private static final BigDecimal PRECISION = new BigDecimal("0.05");

    public static void main(String[] args) {
        BigDecimal value = new BigDecimal("6.23");
        System.out.println("value = " + value + " / rounded = " + roundCurrency(value));
        value = new BigDecimal("6.22");
        System.out.println("value = " + value + " / rounded = " + roundCurrency(value));
        value = new BigDecimal("6.20");
        System.out.println("value = " + value + " / rounded = " + roundCurrency(value));
        value = new BigDecimal("6.19");
        System.out.println("value = " + value + " / rounded = " + roundCurrency(value));
    }

    public static BigDecimal roundCurrency(BigDecimal value) {
        return value.divide(PRECISION, 0, RoundingMode.HALF_DOWN)
                    .multiply(PRECISION);
    }
}
assylias
  • 321,522
  • 82
  • 660
  • 783