Convert string to BigDecimal in java

I read the currency from XMLin Java.

String currency = 135.69;

When I convert this to BigDecimal, I get:

 System.out.println(new BigDecimal(135.69));

Conclusion:

135.68999999999999772626324556767940521240234375.

Why does it display a lot of numbers? How can I avoid this? All I want is output 135.69.

+37
source share
6 answers

The constructor of BigDecimal (double) has some problems, it is preferable to use BigDecimal (String) or BigDecimal.valueOf (double).

System.out.println(new BigDecimal(135.69)); //135.68999999999999772626324556767940521240234375
System.out.println(new BigDecimal("135.69")); // 135.69
System.out.println(BigDecimal.valueOf(135.69)); // 135.69

The BigDecimal (double) documentation explains this behavior:

  • . , BigDecimal (0.1) Java BigDecimal, 0,1 ( 1 1), 0,1000000000000000055511151231257827021181583404541015625. , 0,1 (, , ). , , , 0,1, , .
  • String, , : BigDecimal ( "0.1" ) BigDecimal, 0,1, . , , String .
  • BigDecimal double, , ; , double String Double.toString(double), BigDecimal (String). , valueOf (double).
+76
String currency = "135.69";
System.out.println(new BigDecimal(currency));

//will print 135.69
+24

-. , (2), , , .

+2

You store 135.69 as a string in currency. But instead of passing a variable currency, you again pass 135.69 (double value) to the new BigDecimal (). So you see a lot of numbers in the output. If you pass the currency variable, you will get 135.69

+2
source

BigDecimal b = BigDecimal.valueOf (d);

import java.math.*; 

public class Test { 

    public static void main(String[] args) 
    { 

        // Creating a Double Object 
        Double d = new Double("785.254"); 

        /// Assigning the bigdecimal value of ln to b 
        BigDecimal b = BigDecimal.valueOf(d); 

        // Displaying BigDecimal value 
        System.out.println("The Converted BigDecimal value is: " + b); 
    } 
}
0
source

Hi guys, you cannot convert the string directly to bigdecimal

you need to first convert it to long after that you will convert large decimal

String currency = "135.69"; 
Long rate1=Long.valueOf((currency ));            
System.out.println(BigDecimal.valueOf(rate1));
-5
source

All Articles