My code sample:
import java.math.*;
public class x
{
public static void main(String[] args)
{
BigDecimal a = new BigDecimal("1");
BigDecimal b = new BigDecimal("3");
BigDecimal c = a.divide(b, BigDecimal.ROUND_HALF_UP);
System.out.println(a+"/"+b+" = "+c);
}
}
The result is:
1/3 = 0
What am I doing wrong?
Rohan Grover
You havent specified a scale for the result. Please try this
import java.math.*;
public class x
{
public static void main(String[] args)
{
BigDecimal a = new BigDecimal("1");
BigDecimal b = new BigDecimal("3");
BigDecimal c = a.divide(b,2, BigDecimal.ROUND_HALF_UP);
System.out.println(a+"/"+b+" = "+c);
}
}
this will give the result as 0.33. Please read the API
来源:https://stackoverflow.com/questions/10637232/how-can-i-divide-properly-using-bigdecimal