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的方向舍入
相关文章推荐
- Java中正则表达式和常用的Math、Random、System、BigInteger、BigDecimal、Date/DateFormat、Calendar类的使用
- 达内课程-基本类型包装类BigInteger、BigDecimal使用
- Java BigInteger的简单使用
- java.math中NumberFormat,BigInteger和BigDecimal的简单用法
- java.math中NumberFormat,Math,BigInteger和BigDecimal的简单用法
- 简单常用类:Math 、Random、System、Integer、Character、BigInteger、BigDecimal等
- BigInteger简单使用及方法总结
- Java BigInteger简单使用示例
- java中biginteger和bigdecimal在大数计算中的使用
- BigInteger和BigDecimal大数值类的使用
- java.math.BigInteger使用心得总结
- BigDecimal和BigInteger详解
- BigInteger 与 BigDecimal区别,及BigDecimal详解
- java BigInteger使用
- java.math.BigInteger使用心得总结
- 大数处理类BigInteger和BigDecimal浅谈
- BigInteger与BigDecimal
- java BigInteger和BigDecimal
- java 中的大数据类型(BigInteger和BigDecimal)
- java 中的大数据类型(BigInteger和BigDecimal)