The BigDecimal(double) constructor can have unpredictable behaviors. 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(new BigDecimal("13۵.۶9")); // 135.69
System.out.println(BigDecimal.valueOf(135.69)); // 135.69

The documentation for BigDecimal(double) explains in detail:

  1. The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
  2. The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
  3. When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.
Answer from Marlon Patrick on Stack Overflow
Top answer
1 of 8
185

The BigDecimal(double) constructor can have unpredictable behaviors. 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(new BigDecimal("13۵.۶9")); // 135.69
System.out.println(BigDecimal.valueOf(135.69)); // 135.69

The documentation for BigDecimal(double) explains in detail:

  1. The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
  2. The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
  3. When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.
2 of 8
41
String currency = "135.69";
System.out.println(new BigDecimal(currency));

//will print 135.69
🌐
Baeldung
baeldung.com › home › java › java string › converting string to bigdecimal in java
Converting String to BigDecimal in Java | Baeldung
May 19, 2021 - Using NumberFormat.getCurrencyInstance(Locale.FRANCE) applies these formatting rules automatically, allowing the parser to interpret “348,45 €” correctly and produce the expected BigDecimal value of 348.45. By relying on locale-specific NumberFormat instances, we can accurately handle currency strings from different regions, ensuring reliable numeric conversion in internationalized applications. In this article, we learned that Java provides us with multiple methods to convert String to BigDecimal values.
🌐
Coderanch
coderanch.com › t › 374547 › java › convert-String-BigDecimal
How to convert String to BigDecimal (Java in General forum at Coderanch)
Hi Otrebron, To learn more about the methods of BigDecimal, refer to Java API. Joyce [ September 10, 2004: Message edited by: Joyce Lee ] ... BigDecimal(String val) Translates the string representation of a BigDecimal into a BigDecimal. Guess where I found that info! ... Boost this thread! ... BigDecimal Contsructer Pitfall.
🌐
Coderanch
coderanch.com › t › 385788 › java › converting-String-Bigdecimal
Problem while converting String to Bigdecimal (Java in General forum at Coderanch)
another option may be to use the NumberFormat class to parse the String into a Number. You should be able to construct a BigDecimal from the Number (or its primitive equivalent). The NumberFormat class has methods such as getXXXInstance with overloaded versions that will allow you to use a ...
🌐
Java Guides
javaguides.net › 2019 › 07 › java-conversion-between-bigdecimal-and-string-tutorial.html
How to Convert String into BigDecimal in Java
June 15, 2024 - Converting a String to a BigDecimal in Java can be accomplished using the BigDecimal constructor. It is essential to handle the NumberFormatException to ensure your code is robust and can handle invalid input gracefully.
🌐
Blogger
javahungry.blogspot.com › 2020 › 01 › string-to-bigdecimal.html
2 ways to Convert String to BigDecimal in Java with Examples | Java Hungry
The first step is to convert the String to Double. The second step is to convert Double to BigDecimal, using BigDecimal.valueOf(double) method. As shown in the example below: import java.math.*; public class JavaHungry { public static void main(String args[]) { String str = "123.45"; // Converting ...
🌐
Java2Blog
java2blog.com › home › conversion › java string to bigdecimal
Java convert String to BigDecimal
January 12, 2021 - It is very simple to convert String to BigDecimal in java.
🌐
Coderanch
coderanch.com › t › 451450 › java › Convert-String-BigDecimal
Convert String to BigDecimal (Java in General forum at Coderanch)
(Note that in Java, if you write an integer literal with a leading 0, it's assumed to be a number in octal (base 8!)) ... Gareth Lloyd wrote:Are you trying to convert binary to decimal? In which case a look at the BigInteger constructors might be helpful. Note that is BigInteger, not BigDecimal, but the String ...
🌐
Qlik Community
community.qlik.com › t5 › Talend-Studio › Convert-a-string-to-Big-Decimal › td-p › 2348714
Solved: Convert a string to Big Decimal - Qlik Community - 2348714
November 15, 2024 - Note that you may also need to handle any potential exceptions that can be thrown by the `BigDecimal` constructor, such as `NumberFormatException` if the input string is not a valid decimal number. SkyWard Alpine Login ... Ditto - same here! ... You can use the `BigDecimal` class in Java to convert the string "$6.00" to a `BigDecimal` object.
Find elsewhere
🌐
Softwareag
techcommunity.softwareag.com › t › coverting-string-to-bigdecimal › 174637
Coverting String to BigDecimal - Software AG Adabas & Natural Tech Community & Forums
October 10, 2013 - Can a String be converted to BigDecimal(java.math.BigDecimal) type? I have an input value as a string which is actually a number. I need to pass it to a JDBC adapter service which is accepting only java.math.BigDecimal …
🌐
CodeSpeedy
codespeedy.com › home › how to convert string to bigdecimal in java
How to convert String to BigDecimal in Java - CodeSpeedy
November 22, 2019 - package program; import ... using the BigDecimal() constructor by passing the String as an argument BigDecimal bd1=new BigDecimal(double1); System.out.println("String (double) ---> BigDecimal "+bd1); BigDecimal bd2=new ...
🌐
Jaspersoft Community
community.jaspersoft.com › forum
Convert the String to Big Decimal with format ("##,##0.00") in Jasperreport - Products - Jaspersoft Community
December 5, 2023 - I would like to convert the field from String to Big Decimal with Format ("##,##0.00") in Java. Previously, we got the DataSource from sql, but for now using csv as datasource. it mean all of the fields is using string format.
🌐
Experts Exchange
experts-exchange.com › questions › 11456059 › How-to-convert-String-to-BigDecimal.html
Solved: How to convert String to BigDecimal. | Experts Exchange
July 17, 2000 - Umm, BigDecimal has a string constuctor, which does exactly what you want... Example: BigDecimal decimal = new BigDecimal("1234.567"); Sasha Maryanovsky.
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-create-a-bigdecimal-from-a-string-type-value
Java Program to create a BigDecimal from a string type value
import java.math.BigDecimal; public class Demo { public static void main(String[] argv) throws Exception { BigDecimal one = new BigDecimal("562537627.8787867"); BigDecimal two = BigDecimal.valueOf(562L); one = one.add(two); System.out.println(one); } } ... Another approach is using the BigDecimal.valueOf method. While this method is primarily used for converting primitive types like double or long to BigDecimal, it can be useful in certain scenarios where you're dealing with numeric values that do not require the use of a string constructor.
🌐
SAP Community
community.sap.com › t5 › technology-q-a › how-to-convert-string-value-to-java-lang-bigdecimal › qaq-p › 1116689
How to convert String value to java.lang.BigDecimal
July 9, 2014 - You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in. ... Use BigDecimal("StringValue") constructor. Here string value should represent a valid number
🌐
Experts Exchange
experts-exchange.com › questions › 24899969 › Localized-String-to-BigDecimal.html
Solved: Localized String to BigDecimal | Experts Exchange
November 14, 2009 - ... Sorry for the misconception, but I need to go the other way! So I'll give to example values: String nl_NL_BigDecimal = "343.298.723.948.729.384.0 ... 8"; //This would be the en_US equivalent...
Top answer
1 of 2
49

It seems like there is no other way since java.Lang.Number doesn't have a method which returns a BigDecimal type. Anyway it makes sense because BigDecimal only accepts strings which are properly formatted not like "2.105,88" but like "2105.88".

Let me show your my code:

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class JavaMain {
    public static void main(String[] args) {
        String numberString = "2.105,88";
        //using casting
        try {
            DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
            df.setParseBigDecimal(true);
            BigDecimal bd = (BigDecimal) df.parseObject(numberString);
            System.out.println(bd.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //your way short version
        NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
        try {
            BigDecimal bd1 = new BigDecimal(nf.parse(numberString).toString());
            System.out.println(bd1.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String numberStringFixed = "2105.88";
        //direct string formatted
        System.out.println(new BigDecimal(numberStringFixed));;     
        //direct but erroneous way if the string is not formatted
        System.out.println(new BigDecimal(numberString));;
        
    }
}

I hope this helps!

2 of 2
35

DecimalFormat has a method called setParseBigDecimal that causes parse() to return a BigDecimal. You just need to cast the returned Number.

    String numberString = "2.105,88";

    NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
    if (nf instanceof DecimalFormat) {
        DecimalFormat df = (DecimalFormat) nf;
        df.setParseBigDecimal(true);
        BigDecimal parsed = (BigDecimal) df.parse(numberString);

        System.out.println(parsed);
    }

Output:

2105.88

setParseBigDecimal was introduced in Java 1.5.

🌐
GeeksforGeeks
geeksforgeeks.org › java › bigdecimal-valueof-method-in-java
BigDecimal valueOf() Method in Java - GeeksforGeeks
April 14, 2022 - // Java Program to Illustrate valueOf() ...igDecimal.valueOf(double val) is an inbuilt method in java that translates a double into a BigDecimal, using the double's canonical string representation provided by the Double.toString(double) method...
🌐
The Eclipse Foundation
eclipse.org › forums › index.php › t › 462964
Eclipse Community Forums: ATL » convertion from string to BigDecimal | The Eclipse Foundation
The Eclipse Foundation - home to a global community, the Eclipse IDE, Jakarta EE and over 350 open source projects, including runtimes, tools and frameworks.