Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use BigDecimal in Java

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use BigDecimal in Java". In daily operation, I believe many people have doubts about how to use BigDecimal in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to use BigDecimal in Java". Next, please follow the editor to study!

I. Overview of BigDecimal

The API class BigDecimal provided by Java in the java.math package is used to perform precise operations on numbers with more than 16 significant bits. The double-precision floating-point variable double can handle 16-bit significant numbers, but in practical applications, larger or smaller numbers may need to be operated and processed.

In general, for those numbers that do not need accurate calculation precision, we can directly use Float and Double processing, but Double.valueOf (String) and Float.valueOf (String) will lose precision. So in development, if we need to accurately calculate the results, we must use the BigDecimal class to operate.

What BigDecimal creates is an object, so we can't use the traditional +, -, *, / and other arithmetic operators to perform mathematical operations on its objects directly, but must call their corresponding methods. The parameters in the method must also be objects of BigDecimal. A constructor is a special method of a class that is specifically used to create objects, especially those with parameters.

2. Common constructors of BigDecimal

2.1. Common constructors

BigDecimal (int)

Create an object with the integer value specified by the parameter

BigDecimal (double)

Create an object with a double precision value specified by the parameter

BigDecimal (long)

Create an object with a long integer value specified by the parameter

BigDecimal (String)

Create an object with a numeric value specified by the parameter as a string

2.2. Analysis of usage problems

Examples of use:

BigDecimal a = new BigDecimal (0.1); System.out.println ("a values is:" + a); System.out.println ("="); BigDecimal b = new BigDecimal ("0.1"); System.out.println ("b values is:" + b)

Example of the result:

A values is:0.1000000000000000055511151231257827021181583404541015625 = b values is:0.1

Cause analysis:

1) the result of the construction method whose parameter type is double has some unpredictability. One might think that the BigDecimal created by writing newBigDecimal (0.1) in Java is exactly equal to 0.1 (a non-scalar value of 1 with a scale of 1), but it is actually equal to 0.10000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be accurately represented as double (or, in this case, as any finite length binary decimal). In this way, the value passed into the constructor is not exactly equal to 0.1 (although ostensibly equal to that value).

2) the String constructor is completely predictable: writing newBigDecimal ("0.1") creates a BigDecimal that is exactly equal to the expected 0.1. Therefore, by comparison, it is generally recommended that the String construction method be preferred.

3) when double must be used as the source of BigDecimal, note that this constructor provides an exact conversion; it does not provide the same result as using the Double.toString (double) method, and then using the BigDecimal (String) constructor to convert double to String. To get this result, use the static valueOf (double) method. The official account of Java bosom friend replied to "aggregation of interview questions" and sent you a treasure book of interview questions.

III. Detailed explanation of common methods of BigDecimal

3.1. Common methods

Add (BigDecimal)

The values in the BigDecimal object are added to return the BigDecimal object

Subtract (BigDecimal)

Subtracts the values in the BigDecimal object and returns the BigDecimal object

Multiply (BigDecimal)

Multiplies the values in the BigDecimal object and returns the BigDecimal object

Divide (BigDecimal)

Divides the values in the BigDecimal object and returns the BigDecimal object

ToString ()

Convert a value in a BigDecimal object to a string

DoubleValue ()

Convert values in BigDecimal objects to double-precision numbers

FloatValue ()

Converts a value in a BigDecimal object to a single precision number

LongValue ()

Convert the values in the BigDecimal object to grow integers

IntValue ()

Convert values in BigDecimal objects to integers

3.2.The comparison of BigDecimal size

The compareTo method of bigdemical is generally used to compare the size of BigDecimal in java.

Int a = bigdemical.compareTo (bigdemical2)

Return result analysis:

A =-1, which means bigdemical is less than bigdemical2; a = 0, bigdemical equals bigdemical2; a = 1, bigdemical is greater than bigdemical2

For example: an is greater than or equal to b

New bigdemica (a) .compareto (new bigdemical (b)) > = 0

IV. BigDecimal format

Because the format () method of the NumberFormat class can take a BigDecimal object as its parameter, you can use BigDecimal to format currency values, percentiles, and general values that exceed 16 significant digits.

Take formatting currencies and percentages with BigDecimal as an example. First, the BigDecimal object is created, and after the arithmetic operation of BigDecimal, the references to currency and percentage formatting are established respectively. Finally, the formatted currency value and percentage are output using the BigDecimal object as the parameter of the format () method.

NumberFormat currency = NumberFormat.getCurrencyInstance (); / / establish currency format reference NumberFormat percent = NumberFormat.getPercentInstance (); / establish percentage format reference percent.setMaximumFractionDigits (3); / / percentage decimal point up to 3 digits BigDecimal loanAmount = new BigDecimal ("15000.48"); / / loan amount BigDecimal interestRate = new BigDecimal ("0.008"); / / interest rate BigDecimal interest = loanAmount.multiply (interestRate) / / multiply System.out.println ("loan amount:\ t" + currency.format (loanAmount)); System.out.println ("interest rate:\ t" + percent.format (interestRate)); System.out.println ("interest:\ t" + currency.format (interest))

Results:

Loan amount: ¥15000.48 interest rate: 0.8% interest: ¥120.00

In BigDecimal format, 2 is reserved as a decimal, and if it is insufficient, 0 is added:

Public class NumberFormat {public static void main (String [] s) {System.out.println (formatToNumber (new BigDecimal ("3.435")); System.out.println (formatToNumber (new BigDecimal (0); System.out.println (formatToNumber (new BigDecimal ("0.001")); System.out.println (formatToNumber (new BigDecimal ("0.001") The BigDecimal decimal between System.out.println (formatToNumber (new BigDecimal ("0.006")); System.out.println (formatToNumber (new BigDecimal ("0.206"));} / * * @ desc 1.0: 1. If you lose the preceding 0 after formatting, add 0 directly to the front. * 2. If the parameter passed in is equal to 0, the string "0.00" * 3 is returned directly. If the decimal is greater than 1, direct formatting returns the string * @ return * / public static String formatToNumber (BigDecimal obj) {DecimalFormat df = new DecimalFormat ("# .00"); if (obj.compareTo (BigDecimal.ZERO) = = 0) {return "0.00" } else if (obj.compareTo (BigDecimal.ZERO) > 0&&obj.compareTo (new BigDecimal (1)) 0) res = true; else res = false; return res;}} at this point, the study on "how to use BigDecimal in Java" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report