Java中的高精度整數和高精度小數,java高精度

來源:互聯網
上載者:User

Java中的高精度整數和高精度小數,java高精度

在實際編碼中,會遇到很多高精度的案例,比如,在計算金錢的時候就需要保留高精度小數,這樣計算才不會有太大誤差:

在下面的代碼中,我們驗證了,當兩個float型的數字相加,得到的結果和我們的預期結果是有誤差的,為了減小和防止這種誤差的出現,我們需要使用BigInteger類和BigDecimal類來計算。

package com.ietree.base.number;import java.math.BigDecimal;import java.math.BigInteger;public class BigIntegerTest {    public static void main(String[] args) {        float f1 = 123.01f + 2.01f;        // 預期輸出:125.02,實際輸出:125.020004        System.out.println(f1);        // 預期輸出:125.02,實際輸出:125.02000000000001        System.out.println(123.01 + 2.01);        System.out.println("===============================");        // 高精度整數測試        BigInteger bint1 = new BigInteger("125");        BigInteger bint2 = new BigInteger("999");        BigInteger tmp;        // 相加        tmp = bint1.add(bint2);        System.out.println("bint1 + bint2 = " + tmp);        // 相減        tmp = bint2.subtract(bint1);        System.out.println("bint2 - bint1 = " + tmp);        // 相乘        tmp = bint1.multiply(bint2);        System.out.println("bint1 * bint2 = " + tmp);        // 相除        tmp = bint2.divide(bint1);        System.out.println("bint2 / bint1 = " + tmp);        // 求餘數        tmp = bint2.remainder(bint1);        System.out.println("bint2 % bint1 = " + tmp);        // 求次方        tmp = bint2.pow(2);        System.out.println("bint2的二次方 = " + tmp);        System.out.println("======================================");        // 高精度小數測試        BigDecimal bd1 = new BigDecimal(123.01);        BigDecimal bd2 = new BigDecimal(2.01);        BigDecimal bd;        // 相加        bd = bd1.add(bd2);        System.out.println("bd1 + bd2 = " + bd);        // 相減        bd = bd1.subtract(bd2);        System.out.println("bd2 - bd1 = " + bd);        // 相乘        bd = bd1.multiply(bd2);        System.out.println("bd1 * bd2 = " + bd);        // 相除        // bd = bd1.divide(bd2);        bd = bd1.divide(new BigDecimal(2.0));        System.out.println("bd1 / 2.0 = " + bd);        // 求餘數        bd = bd1.remainder(bd2);        System.out.println("bd2 % bd1 = " + bd);        // 求次方        bd = bd1.pow(3);        System.out.println("bd2的三次方 = " + bd);        System.out.println("======================================");        // 四捨五入保留小數位元        BigDecimal bd3 = new BigDecimal(123.01).setScale(5,5);        System.out.println("bd3 = " + bd3);    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.