[JAVA] Big Decimal memorandum of always int beginner

Introduction

I have been learning Java for 3 months. I am doing Spring in training, but if the data type is Number I used Big Decimal instead of int for things that are only integers. Speaking of numbers, I used only ints or doubles, and I was confused about the processing of BigDecimal. There are many articles that are well organized about BigDecimal, I will summarize only the ones I actually used as a memorandum.

I want to calculate

The four arithmetic operations are not "+", "-", "*", or "/".

Calculation Method Example
Addition (A+ B) add A.add(B)
Subtraction (A- B) subtract A.subtract(B)
Multiplication (A* B) multiply A.multiply(B)
Gradual calculation (A/ B) divide A.divide(B)

I haven't used gradual calculation, but if it's a decimal number, I need three arguments. A.divide (B, number of digits after the decimal point, rounding method (rounding up, rounding down, rounding, etc.)) I haven't used it this time, so I'll omit it.

I want to compare

Use "compareTo".

Comparison operator Return value Example
A < B If A is less than B-Returns 1 A.compareTo(B) < 0
A > B Returns 1 if A is greater than B A.compareTo(B) > 0
A == B Returns 0 if A and B are equal A.compareTo(B) == 0

When I looked it up in the training, I wanted to make it "less than (<=") instead of "smaller (<)", so I wrote it like this.

//Not "greater than" (it will mess up your head)
if (!(A.compareTo(B) == 1)) {
}

//I think this was good
if (A.compareTo(B) <= 0) {
}

Big Decimal ↔︎ String conversion

Since I also received the input value in String type and converted it to BigDecimal for processing, I will describe it.

BigDecimal→String

String String type variable name=Big Decimal type.toString();

String→BigDecimal

BigDecimal BigDecimal type variable name= new BigDecimal(String type);

reference

https://docs.oracle.com/javase/jp/11/docs/api/java.base/java/math/BigDecimal.html https://www.sejuku.net/blog/25564 https://techacademy.jp/magazine/31915

Recommended Posts

Big Decimal memorandum of always int beginner
Java Big Decimal
[Ruby] Big Decimal and DECIMAL