您的位置:首页 > 其它

BigInteger和BigDecimal的简单使用

2014-11-26 16:13 281 查看
</pre><p><pre name="code" class="java">import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;

public class Rational {
public static void main(String [] args){
/*float和double只能用来做科学计算或者是工程计算,在商业计算中要
用java.math.BigDecimal。BigDecimal所创建的是对象,我
们不能使用传统的+、-、*、/等算术运算符直接对其对象进行数学运算,而
必须调用其相对应的方法。*/

//将十进制的字符串转换为BigInteger
BigInteger big1=new BigInteger("623");
BigInteger big2=new BigInteger("21");

//加法运算
System.out.println(big1.add(big2));
//减法运算
System.out.println(big1.subtract(big2));
//乘法运算
System.out.println(big1.multiply(big2));
//除法运算
System.out.println(big1.divide(big2));

//大数运算之求最大公约数,最小公倍数
System.out.println("最大公约数"+big1.gcd(big2));
//(a*b)/(a和b的最大公约数)
System.out.println("最小公倍数"+big1.multiply(big2).divide(big1).gcd(big2));

BigDecimal bigdec1=new BigDecimal("1");
BigDecimal bigdec2=new BigDecimal("3");

/*BigDecimal 类使用户能完全控制舍入行为。如果未指定舍入模式,并
且无法表示准确结果,则抛出一个异常*/
//确定舍入的匹配模式,MathContext(3, RoundingMode.HALF_DOWN);
//设置指定要返回的总位数;这确定了结果的精度。3表示从最左边开始的非零数字开始
MathContext mc = new MathContext(3, RoundingMode.HALF_DOWN);
//做除法运算
System.out.println(bigdec1.divide(bigdec2,mc));
}
}


附上RoundingMode类舍入类型的介绍

ROUND_CEILING

Rounding mode to round towards positive infinity.

向正无穷方向舍入

ROUND_DOWN

Rounding mode to round towards zero.

向零方向舍入

ROUND_FLOOR

Rounding mode to round towards negative infinity.

向负无穷方向舍入

ROUND_HALF_DOWN

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.

向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向下舍入, 例如1.55 保留一位小数结果为1.5

ROUND_HALF_EVEN

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,如果保留位数是奇数,使用ROUND_HALF_UP ,如果是偶数,使用ROUND_HALF_DOWN

ROUND_HALF_UP

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向上舍入, 1.55保留一位小数结果为1.6

ROUND_UNNECESSARY

Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.

计算结果是精确的,不需要舍入模式

ROUND_UP

Rounding mode to round away from zero.

向远离0的方向舍入
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: