Using Java BigDecimal Still Doesn't Solve Correctly

I have a method with two values ​​entered double. When I try to add them together, I get the wrong values ​​over a specific threshold, so I started using it BigDecimal.

However, even with BigDecimalI still have the wrong values?

double value1 = 2789.45;
double value2 = 557.89;
System.out.println(BigDecimal.valueOf(value1 + value2));

prints

3347.3399999999997

when he should read how

3347.34

How can I do it right, even if value1it value2can be higher than the current area? (they are calculated by a separate method).

Should rounding be used?

+4
source share
3 answers

Should rounding be used?

NOPE, , , double sum.


(value1 + value2) ( ) BigDecimal.

, :

double value1 = 2789.45;
double value2 = 557.89;
System.out.println(BigDecimal.valueOf(value1).add(BigDecimal.valueOf(value2)));

:

3347.34

IDEONE DEMO


UPDATE

-1. BigDecimal.valueOf, , BigDecimal new BigDecimal("2789.45"), new BigDecimal("557.89"). double, . BigDecimal.valueOf , . - Louis Wasserman

. , , , ( OP) String, double:

String value1 = "2789.45"; 
BigDecimal one = new BigDecimal(value1);
String value2 = "557.89";
BigDecimal two = new BigDecimal(value2);
System.out.println(one.add(two));

:

3347.34

Louis Wasserman.

+8

, doubles, , , , , ,

double value1 = 2789.45;
double value2 = 557.89;
double sum = value1 + value2; // precision lost here
System.out.println(BigDecimal.valueOf(sum));
+1

.

:

import java.math.BigDecimal;

public class Test {
  public static void main(String[] args) {
    System.out.println(new BigDecimal(2789.45));
    System.out.println(new BigDecimal("2789.45"));
  }
}

:

2789.4499999999998181010596454143524169921875
2789.45

BigDecimal , double, , .

+1

Source: https://habr.com/ru/post/1613821/


All Articles