Parsing string to bigdecimal in java

2 ways to Convert String to BigDecimal in Java with Examples

In this tutorial, I will be sharing how to convert String to BigDecimal in java with examples. There are two ways to achieve it.

1. Using Constructor of Big Decimal class [Recommended]

2. Using BigDecimal.valueOf() method

1. Using Constructor of Big Decimal

This is the easiest way to convert String to BigDecimal in java. Just use BigDecimal(String) constructor.

BigDecimal obj = new BigDecimal(String);

The above line will do the job. You can find the example below:

import java.math.*; public class JavaHungry  public static void main(String args[])  String str = "123.45"; // Using BigDecimal(String) constructor BigDecimal num = new BigDecimal(str); // Printing BigDecimal value System.out.println("Converted String to BigDecimal : " + num); > > 

Output:
Converted String to BigDecimal : 123.45

Note: String passed in a constructor should be a valid number otherwise NumberFormatException will be thrown.

2. Using BigDecimal.valueOf() method

Convert String to BigDecimal by using BigDecimal.valueOf(double) method.
It is a two-step process. 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 String to Double Double obj = new Double(str); // Converting Double to BigDecimal BigDecimal num = BigDecimal.valueOf(obj); // Printing BigDecimal value System.out.println("Converted String to BigDecimal: " + num); > > 

Output:
Converted String to BigDecimal: 123.45

Note: BigDecimal.valueOf(double) is a static method. You do not need to create a BigDecimal object to access it.

That’s all for the day. Please mention in comments in case you have any questions related to convert String to BigDecimal in java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Converting String to BigDecimal in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this tutorial, we’ll cover many ways of converting String to BigDecimal in Java.

2. BigDecimal

BigDecimal represents an immutable arbitrary-precision signed decimal number. It consists of two parts:

  • Unscaled value – an arbitrary precision integer
  • Scale – a 32-bit integer representing the number of digits to the right of the decimal point

For example, the BigDecimal 3.14 has an unscaled value of 314 and a scale of 2.

If zero or positive, the scale is the number of digits to the right of the decimal point.

If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. Therefore, the value of the number represented by the BigDecimal is (Unscaled value × 10 -Scale ).

The BigDecimal class in Java provides operations for basic arithmetic, scale manipulation, comparison, format conversion, and hashing.

Furthermore, we use BigDecimal for high-precision arithmetic, calculations requiring control over the scale, and rounding off behavior. One such example is calculations involving financial transactions.

We can convert a String into BigDecimal in Java using one of the below methods:

  • BigDecimal(String) constructor
  • BigDecimal.valueOf() method
  • DecimalFormat.parse() method

Let’s discuss each of them below.

3. BigDecimal(String)

The easiest way to convert String to BigDecimal in Java is to use BigDecimal(String) constructor:

BigDecimal bigDecimal = new BigDecimal("123"); assertEquals(new BigDecimal(123), bigDecimal);

4. BigDecimal.valueOf()

We can also convert String to BigDecimal by using the BigDecimal.valueOf(double) method.

This is a two-step process. The first step is to convert the String to Double. The second step is to convert Double to BigDecimal:

BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf("123.42")); assertEquals(new BigDecimal(123.42).setScale(2, BigDecimal.ROUND_HALF_UP), bigDecimal);

It must be noted that some floating-point numbers can’t be exactly represented using a Double value. This is because of the in-memory representation of floating-point numbers of type Double. Indeed, the number is represented in a rational form approaching the entered Double number as much as possible. As a result, some floating-point numbers become inaccurate.

5. DecimalFormat.parse()

When a String representing a value has a more complex format, we can use a DecimalFormat.

For example, we can convert a decimal-based long value without removing non-numeric symbols:

BigDecimal bigDecimal = new BigDecimal(10692467440017.111).setScale(3, BigDecimal.ROUND_HALF_UP); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setGroupingSeparator(','); symbols.setDecimalSeparator('.'); String pattern = "#,##0.0#"; DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols); decimalFormat.setParseBigDecimal(true); // parse the string value BigDecimal parsedStringValue = (BigDecimal) decimalFormat.parse("10,692,467,440,017.111"); assertEquals(bigDecimal, parsedStringValue);

The DecimalFormat.parse method returns a Number, which we convert to a BigDecimal number using the setParseBigDecimal(true).

Usually, the DecimalFormat is more advanced than we require. Thus, we should favor the new BigDecimal(String) or the BigDecimal.valueOf() instead.

6. Invalid Conversions

Java provides generic exceptions for handling invalid numeric Strings.

Notably, new BigDecimal(String), BigDecimal.valueOf(), and DecimalFormat.parse throw a NullPointerException when we pass null:

@Test(expected = NullPointerException.class) public void givenNullString_WhenBigDecimalObjectWithStringParameter_ThenNullPointerExceptionIsThrown() < String bigDecimal = null; new BigDecimal(bigDecimal); >@Test(expected = NullPointerException.class) public void givenNullString_WhenValueOfDoubleFromString_ThenNullPointerExceptionIsThrown() < BigDecimal.valueOf(Double.valueOf(null)); >@Test(expected = NullPointerException.class) public void givenNullString_WhenDecimalFormatOfString_ThenNullPointerExceptionIsThrown() throws ParseException

Similary, new BigDecimal(String) and BigDecimal.valueOf() throw a NumberFormatException when we pass an invalid String that can’t be parsed to a BigDecimal (such as &):

@Test(expected = NumberFormatException.class) public void givenInalidString_WhenBigDecimalObjectWithStringParameter_ThenNumberFormatExceptionIsThrown() < new BigDecimal("&"); >@Test(expected = NumberFormatException.class) public void givenInalidString_WhenValueOfDoubleFromString_ThenNumberFormatExceptionIsThrown()

Lastly, DecimalFormat.parse throws a ParseException when we pass an invalid String:

@Test(expected = ParseException.class) public void givenInalidString_WhenDecimalFormatOfString_ThenNumberFormatExceptionIsThrown() throws ParseException

7. Conclusion

In this article, we learned that Java provides us with multiple methods to convert String to BigDecimal values. In general, we recommend using the new BigDecimal(String) method for this purpose.

As always, the code used in this article can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

How to convert String to BigDecimal in Java

Hey Everyone! In this article, we will learn how to convert String to BigDecimal in Java.
Before directly getting into the code let us first understand BigDecimal class in Java.

BigDecimal Java

The BigDecimal class in java is used for various operations such as arithmetic, rounding, hashing, comparison, and manipulation operations. It is present in the java.math.BigDecimal package in java. The BigDecimal class is usually used where precise rounding off operations are required such as when dealing with financial or statistical data. The BigDecimal class consists of various constructors and methods that are used for the precise operations to be performed.
Example:-

package program; import java.math.BigDecimal; public class Program < public static void main(String[] args) < int n,m; BigDecimal bd1 = new BigDecimal("8763"); BigDecimal bd2 = new BigDecimal("7276"); n=bd1.intValueExact(); m = bd2.intValue(); System.out.println("Exact Integer value is "+n); System.out.println( "Integer value EnlighterJSRAW" data-enlighter-theme="classic">run: Exact Integer value is 8763 Integer value = 7276 BUILD SUCCESSFUL (total time: 0 seconds)

Program to convert String to BigDecimal in Java

package program; import java.math.BigDecimal; public class Program < public static void main(String[] args) < //creating various string variables such as integer double and long datatype variables String double1="13.23"; String int1="334"; String long1 = "12323982782"; //converting the string to bigdecimal 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 BigDecimal(int1); System.out.println("String (int) ---> BigDecimal "+bd2); BigDecimal bd3=new BigDecimal(long1); System.out.println("String (long) ---> BigDecimal "+bd3); > >
String (double) ---> BigDecimal 13.23 String (int) ---> BigDecimal 334 String (long) ---> BigDecimal 12323982782

In the above program, the String Variables are converted to BigDecimal using the BigDecimal constructor.

I hope this article was useful to you. Please leave a comment down below in case of any doubts or suggestions.

Источник

Читайте также:  What is perl php python
Оцените статью