Created
October 23, 2011 15:01
-
-
Save joellobo/1307448 to your computer and use it in GitHub Desktop.
Arredondamento
This file contains hidden or 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; | |
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