Skip to main content
deleted 605 characters in body
Source Link
Raffaele
  • 20.9k
  • 7
  • 50
  • 90

I think you should double check your spec, because the requirement is uncommon. Anyway, I think this does what you (seem to) need:

public class Rounding { public static void main(String... args) { BigDecimal round("1.125"); // 1.13 BigDecimal n, int round("1.124"scale); // 1.13{   if round("1n.123"scale(); // 1.12 } public static void round(String> strscale) {   BigDecimal base = newreturn BigDecimalround(str)n.setScale(2, RoundingModen.DOWN); BigInteger intermediate = new BigDecimalscale(str)  - .setScale(31, BigDecimal.ROUND_DOWN)  .movePointRight(3) RoundingMode.toBigInteger(HALF_UP) , .mod(BigInteger.TENscale);   Number result = base; if (intermediate.intValue()} >=else 4){   result = base.add(new BigDecimal("0.01"));  return System.out.println(Stringn.formatsetScale("%.2f"scale, result)RoundingMode.UNNECESSARY); } } 

I think you should double check your spec, because the requirement is uncommon. Anyway, I think this does what you (seem to) need:

public class Rounding { public static void main(String... args) {  round("1.125"); // 1.13  round("1.124"); // 1.13   round("1.123"); // 1.12 } public static void round(String str) {   BigDecimal base = new BigDecimal(str).setScale(2, RoundingMode.DOWN); BigInteger intermediate = new BigDecimal(str)  .setScale(3, BigDecimal.ROUND_DOWN)  .movePointRight(3) .toBigInteger()  .mod(BigInteger.TEN);   Number result = base; if (intermediate.intValue() >= 4)   result = base.add(new BigDecimal("0.01"));  System.out.println(String.format("%.2f", result)); } } 

I think you should double check your spec, because the requirement is uncommon. Anyway, I think this does what you (seem to) need:

public BigDecimal round(BigDecimal n, int scale) { if (n.scale() > scale) { return round(n.setScale(n.scale() - 1, RoundingMode.HALF_UP), scale); } else { return n.setScale(scale, RoundingMode.UNNECESSARY); } } 
Source Link
Raffaele
  • 20.9k
  • 7
  • 50
  • 90

I think you should double check your spec, because the requirement is uncommon. Anyway, I think this does what you (seem to) need:

public class Rounding { public static void main(String... args) { round("1.125"); // 1.13 round("1.124"); // 1.13 round("1.123"); // 1.12 } public static void round(String str) { BigDecimal base = new BigDecimal(str).setScale(2, RoundingMode.DOWN); BigInteger intermediate = new BigDecimal(str) .setScale(3, BigDecimal.ROUND_DOWN) .movePointRight(3) .toBigInteger() .mod(BigInteger.TEN); Number result = base; if (intermediate.intValue() >= 4) result = base.add(new BigDecimal("0.01")); System.out.println(String.format("%.2f", result)); } }