Some problems in the calculation of double floating-point numbers, and the use of bigDecimal

test you

Let me start with a few simple questions.

System.out.println(1/5); What is the output result?

Answer to Question 1

System.out.println(null-0.0); What is the output result?

Answer to Question 2

double part

If a double calculation is null, will it report an error?

Double d1=0.0;
Double d2=1.0;
Double result=d1-d2;

The actual measurement reports an error. Therefore, the non-null check must be performed before the calculation of the double type.
It should be noted here that if it is not set null, the initialized value is 0.0, and no error is reported.

The double type sets the denominator to 1

Because if the denominator is 0.0, then the result will be Infinity.
So it is best to set it to another value.

Double d1=0.0;
Double d2=1.0;
Double result=d1/(d2!=0?d2:1.0);

BigDecimal part

Why use BigDecimal

Floating point calculation in java is not very accurate, BigDecimal can solve this problem very well.

Format decimal places

BigDecimal's support for this is still very good. For example, set to 6 decimal places.

private BigDecimal amount;

this.amount=new BigDecimal(0.0).setScale(6,BigDecimal.ROUND_HALF_UP);

Answer part

Answer to Question 1

Topic 1: System.out.println(1/5); What is the output result?

Not the expected 0.2, but 0.
Because 1/5 is written as an integer division, the decimal places will be ignored. So the result is 0.

If you want to return 0.2, either of the following two types can be used.

Adding .0 means floating-point number, and floating-point calculation will be performed:
1.0/5
adding d means it is double floating-point type, and floating-point calculation will be performed:
1d/5

Answer to Question 2:

Topic 2: System.out.println(null-0.0); What is the output result?

Is it outputting 0?
No, an error will be reported. Because floating-point numbers cannot be null when calculating.

other

Guess you like

Origin blog.csdn.net/enthan809882/article/details/113939618