Converting String to BigDecimal in Java – 在Java中把字符串转换成BigDecimal

最后修改: 2021年 5月 19日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

在本教程中,我们将介绍在Java中把String转换为BigDecimal的许多方法。

2. BigDecimal

2、BigDecimal

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

BigDecimal表示一个不可改变的任意精度的有符号十进制数。它由两部分组成。

  • 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.

例如,BigDecimal 3.14的未标度值为314,标度为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).

如果是负数,则该数的未标定值要乘以10,即比例的负数的幂。因此,BigDecimal代表的数字的值是(未缩放的值×10-Scale

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

Java中的BigDecimal类提供了基本算术、刻度操作、比较、格式转换和散列的操作。

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.

此外,我们将BigDecimal用于高精度的算术,需要控制比例的计算,以及四舍五入的行为。一个这样的例子是涉及金融交易的计算。

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

我们可以在Java中使用以下方法将String转换成BigDecimal

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

Let’s discuss each of them below.

下面我们来逐一讨论。

3. BigDecimal(String)

3.BigDecimal(String)

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

在Java中,将String转换为BigDecimal的最简单方法是使用BigDecimal(String)构造函数。

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

4. BigDecimal.valueOf()

4.BigDecimal.valueOf()

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

我们也可以通过使用String转换为BigDecimalBigDecimal.valueOf(double)方法。

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:

这是一个两步的过程。第一步是将String转换为Double。第二步是将Double转换成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.

必须注意的是,有些浮点数不能用Double值来准确表示。这是因为Double类型的浮点数在内存中的表示方法。事实上,数字的表示方式是尽量接近输入的Double数字的有理形式。因此,一些浮点数变得不准确

5. DecimalFormat.parse()

DecimalFormat.parse() 5.

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

当代表一个值的String有一个更复杂的格式时,我们可以使用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).

DecimalFormat.parse方法返回一个Number,我们使用setParseBigDecimal(true)将其转换为BigDecimal 数字。

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

通常,DecimalFormat比我们要求的更高级。因此,我们应该倾向于使用new BigDecimal(String)或者BigDecimal.valueOf()来代替。

6. Invalid Conversions

6.无效的转换

Java provides generic exceptions for handling invalid numeric Strings.

Java为处理无效的数字Strings提供了通用异常。

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

值得注意的是,new BigDecimal(String), BigDecimal.valueOf(), 和DecimalFormat.parse 当我们传递null时,会抛出NullPointerException

@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 {
    new DecimalFormat("#").parse(null);
}

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 &):

同样,new BigDecimal(String) BigDecimal.valueOf()在我们传递一个无效的String,无法解析为BigDecimal(如&)时,会抛出一个NumberFormatException

@Test(expected = NumberFormatException.class)
public void givenInalidString_WhenBigDecimalObjectWithStringParameter_ThenNumberFormatExceptionIsThrown() {
    new BigDecimal("&");
}

@Test(expected = NumberFormatException.class)
public void givenInalidString_WhenValueOfDoubleFromString_ThenNumberFormatExceptionIsThrown() {
    BigDecimal.valueOf(Double.valueOf("&"));
}

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

最后,DecimalFormat.parse当我们传递一个无效的String时,抛出一个ParseException

@Test(expected = ParseException.class)
public void givenInalidString_WhenDecimalFormatOfString_ThenNumberFormatExceptionIsThrown()
  throws ParseException {
    new DecimalFormat("#").parse("&");
}

7. Conclusion

7.结语

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.

在这篇文章中,我们了解到,Java为我们提供了多种方法来将String转换为BigDecimal值。一般来说,我们推荐使用new BigDecimal(String) 方法来实现这一目的。

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

一如既往,本文中所使用的代码可以在GitHub上找到over