Java double type addition precision problem

Recently, I used double type addition in my work, and found that there was a problem with the accuracy of the result.

The answer is obtained after verification by Baidu, which is hereby recorded.


When adding data of double type, use the + sign directly, and the result will have a precision error
So you need to use the BigDecimal function for operation
double v1 = 4.5;
double v2 = 4.55;
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
double sum= b1.add(b2).doubleValue();



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326886651&siteId=291194637