Skip to content

Instantly share code, notes, and snippets.

@joellobo
Created October 23, 2011 15:01
Show Gist options
  • Save joellobo/1307448 to your computer and use it in GitHub Desktop.
Save joellobo/1307448 to your computer and use it in GitHub Desktop.
Arredondamento
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Teste1 {
/**
* @param args
*/
public static void main(String[] args) {
BigDecimal b1 = new BigDecimal("0.2");
BigDecimal b2 = new BigDecimal("0.5");
BigDecimal b3 = new BigDecimal("0.6");
System.out.println(arr(b1));
System.out.println(arr(b2));
System.out.println(arr(b3));
}
private static String arr(BigDecimal b) {
String r = "";
BigDecimal bb = b.multiply(new BigDecimal("2"));
try {
bb.intValueExact();
r = b.toString();
} catch (Exception e) {
try {
BigDecimal bg = b.setScale(0,RoundingMode.UNNECESSARY);
r = bg.toString();
} catch (ArithmeticException ee) {
BigDecimal bg = b.setScale(0,RoundingMode.HALF_UP);
r = bg.toString();
}
}
return r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment