Java入門–BigDecimalで足し算、引き算等の操作

javaコード:
import java.math.BigDecimal;
public class BigDecimalChk {

public void useCalu(){
System.out.println(0.05+0.01);
System.out.println(1.0-0.42);
System.out.println(4.015*100);
System.out.println(123.3/100);
}

/**
* compare
*/
public void useCaluCompare(){
BigDecimal db = new BigDecimal(0.05+0.01);
System.out.println(db);

System.out.println(“==============");
BigDecimal db1 = new BigDecimal(“0.05");
BigDecimal db2 = new BigDecimal(“0.01");
System.out.println(db1.add(db2));
}

/**
* accuracy test
*/
public void accuracyTest(){
BigDecimal bd= new BigDecimal(1.00);
System.out.println(bd);

System.out.println(“==============");
bd = bd.setScale(2, BigDecimal.ROUND_HALF_EVEN); //bank algorithm
System.out.println(bd);
}

/**
* add
*/
public void add(){
BigDecimal bd1 = new BigDecimal(“3.14");
BigDecimal bd2 = new BigDecimal(“3.42");
System.out.println(bd1.add(bd2));
}

/**
* sub
*/
public void sub(){
BigDecimal bd1 = new BigDecimal(“3.14");
BigDecimal bd2 = new BigDecimal(“3.42");
System.out.println(bd1.subtract(bd2));
}

/**
* mut
*/
public void mut(){
BigDecimal bd1 = new BigDecimal(“3.14");
BigDecimal bd2 = new BigDecimal(“3.42");
System.out.println(bd1.multiply(bd2));
}

/**
* divide
*/
public void div(){
BigDecimal bd1 = new BigDecimal(“-2.1331");
BigDecimal bd2 = new BigDecimal(“2.39877");
System.out.println(bd1.divide(bd2, BigDecimal.ROUND_CEILING));
System.out.println( bd1.divideToIntegralValue(bd2) );
}

/**
* abs
*/
public void abs(){
BigDecimal bd1 = new BigDecimal(“-3.1431");
System.out.println(bd1.abs());
}

/**
* doubleValue
*/
public void doubleValue(){
BigDecimal bd1 = new BigDecimal(“-3.14312");
System.out.println(bd1.doubleValue());
}

/**
* doubleValue
*/
public void compareTo(){
BigDecimal bd1 = new BigDecimal(“-3.14312");
BigDecimal bd2 = new BigDecimal(“3.14312");
System.out.println(bd1.compareTo(bd2));
}

/**
* tostring
*/
public void tostring(){
BigDecimal bd1 = new BigDecimal(3.14);
System.out.println(bd1.toPlainString());
System.out.println(bd1.toString());

System.out.println(“====");
BigDecimal bd2 = new BigDecimal(“-2.1331");
BigDecimal bd3 = new BigDecimal(“2.39877");
System.out.println( bd2.divideToIntegralValue(bd3));
System.out.println( bd2.divideToIntegralValue(bd3).toString());
System.out.println( bd2.divideToIntegralValue(bd3).toPlainString());
}

/**
* max
*/
public void max(){
BigDecimal bd2 = new BigDecimal(“-2.1331");
BigDecimal bd3 = new BigDecimal(“2.39877");
System.out.println(bd2.max(bd3));
System.out.println(bd3.max(bd2));
}

/**
* main
*/
public static void main(String[] args){
BigDecimalChk test = new BigDecimalChk();
// test.useCalu();
// test.useCaluCompare();

// test.accuracyTest();
// test.add();
// test.sub();
// test.mut();
// test.div();

// test.abs();
// test.doubleValue();
// test.compareTo();
// test.tostring();
test.max();
}
}

Java

Posted by arkgame