About java BigDecimal basic usage of the Math

BigDecimal Java API class java.math provided in the package, the number of significant bits used for more than 16 accurate calculation. Double precision floating-point variables can handle 16-bit significand.

In practical applications, the need for a larger or smaller number of computing and processing. float and double can only be used for scientific computing or engineering calculations, use java.math.BigDecimal in business calculations.

BigDecimal objects are created, we can not use traditional +, -, *, /, etc. Arithmetic operators perform mathematical operations on its direct object, and must call its corresponding method.

Method parameters must also be BigDecimal object. Class constructor is a special method, designed to create objects, particularly objects with parameters.

 

import java.math.BigDecimal;
public class T {
    public static void main(String[] args) {
        String a = "9999.9999";
        int b = 9999;
        double c = 9999.9999;
        char d = 99;
        System.out.println("===================");
        // 不同类型转为BigDecimal
        BigDecimal ma = new BigDecimal(a);
        BigDecimal mb = new BigDecimal(b);
        BigDecimal mc = new BigDecimal(c);
        BigDecimal md = new BigDecimal(d);
        System.out.println("ma:"+ma.toString());
        System.out.println("mb:"+mb.toString());
        System.out.println("mc:"+mc.toString());
        System.out.println("md:"+md.toString());
        System.out.println("===================");
        // 加
        BigDecimal add = ma.add(mb);
        System.out.println("加法:"+add);
        // 减
        BigDecimal sub = ma.subtract(mb);
        System.out.println("减法:"+sub);
        // 乘
        BigDecimal mul = mb.multiply(md);
        System.out.println("乘法:"+mul);
        // 除
        BigDecimal div = mb.divide(md);
        System.out.println("除法:"+div);
        System.out.println("===================");
        mc = mc.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println ( "rounded:" + mc);
        System.out.println("===================");
        mc = mc.negate();
        System.out.println("负数:"+mc);
        System.out.println("===================");
    }
}

 

String BigDecimal and mutual conversion:

/ * Number constructed by the method of BigDecimal string 
* BigDecimal provided a method of decimal digits 
* / 
Import java.math.BigDecimal; 
// numeric string 
String StrBd = "1048576.1024"; 
// string configured content value BigDecimal type variable BD 
BigDecimal BD = new new BigDecimal (StrBd); 
// decimal places, decimals is first variable, the second variable is the method of choice (rounded) 
BD = bd.setScale (2, BigDecimal. as ROUND_HALF_UP); 
// output into a string 
string outString = bd.toString ();

  

Guess you like

Origin www.cnblogs.com/ZJOE80/p/10978289.html