I am trying make a multiplication of a BigDecimal number with a precision of 8 digits
Here is what I want to take
0.02749639
This is my code
double amount = 2120;
double BuyPrice = 0.00001297;
BigDecimal result=BigDecimal.valueOf(BuyPrice).multiply(BigDecimal.valueOf(amount)).setScale(8,RoundingMode.HALF_DOWN);
System.out.println(result);
and here what did I took
0.027496400
Can someone help me to fix it?
0.0274964 is the right result. Perhaps in some other part of your code you have already lost precision due to using double
?
When you use BigDecimal.valueOf(double)
you are experiencing a precision loss when you declare the double
. To avoid it one should use new BigDecimal(String)
constructor:
BigDecimal d1 = BigDecimal.valueOf(90.000000000000001d);
BigDecimal d2 = BigDecimal.valueOf(90.000000000000002d);
System.out.println(d1.equals(d2));
BigDecimal s1 = new BigDecimal("90.000000000000001");
BigDecimal s2 = new BigDecimal("90.000000000000002");
System.out.println(s1.equals(s2));
Will print
true
false