標籤:hal static 算術 ide 長度 val 序列 int 包含
如果基本的整數和浮點數精度不能夠滿足需求,那麼可以使用java.math包中的兩個很有平有用的類:BigInteger和BigDecimal。這兩個類可以處理包含任意長度數字序列的數值。
BigInteger類實現了任意精度的
整數運算
BigDecimal實現了任意精度的
浮點數運算 使用靜態valueOf方法可以將普通的數值轉換為大數值:BigInteger a = BigInteger.valueOf(100);遺憾的是,不能使用人們熟悉的算術運算子(+ *)處理大數值。而需要使用大數值類中的add和multiply方法 BigInteger c = a.add(b) //c = a + bBigInteger d = c.multiply(b.add(BigInteger.valueOf(2))) // d = c * ( b + 2 ) Java.math.BigInteger 1.1BigInteger add(BigInteger other)BigInteger subtract(BigInteger other)BigInteger multiply(BigInteger other)BigInteger divide(BigInteger other)BigInteger mod(BigInteger other)返回這個大整數和另一個大整數other的和、差、積、商以及餘數 int compareTo(BigInteger other)=other 返回 0 <other返回負數 否則返回正數 static BigInteger valueOf(long x)傳回值等於x的大整數
java.math. BigDecimal 1.1BigDecimal add(BigDecimal other)BigDecimal subtract(BigDecimal other)BigDecimal multiply(BigDecimal other)BigDecimal divide(BigDecimal other RoundingMode mode) 5.0返回這個大實數和另一個大實數other的和、差、積、商要想計算商,必須給出舍入方式。RoundingMode.HALF_UP是四捨五入方式 int compareTo(BigDecimal other)=other 返回0 <other 返回負數 否則返回正數 staitc BigDecimal valueOf(long x)staitc BigDecimal valueOf(long x,int scale)傳回值為x或x/10scale的一個大實數
Java基礎文法<五> 大數值BigInteger BigDecimal