To you who suffer from unexpected decimal points in Java


Good evening. Again. It's been a long time since my last post. .. ..

In this article, I will describe how to use BigDecimal, which makes the calculation after the decimal point accurate in Java. I will not touch on why the calculation after the decimal point can be done accurately, so I hope you can find out by yourself. I hope it will be helpful for those who want to calculate after the decimal point accurately.

Four arithmetic operations using Big Decimal (basic)

Now, let's write about the basic Big Decimal description method. To use BigDecimal


import java.math.BigDecimal;

Need to be imported. Since it is a standard library, there is no need to bring it from the outside and it can be used immediately. The description method and usage example are shown below.

Four arithmetic operations Description method
Addition add
Subtraction subtract
Multiply multiply
division divide

import java.math.BigDecimal;
public class Main {
    public static void main(String[] args) {
        //Value definition
        int one = 1;
        int two = 2;
        BigDecimal three = BigDecimal.valueOf(3);
        BigDecimal five = BigDecimal.valueOf(5);


        //A little applied

Such a description is possible. Also, as shown in the application of the comment part, it is possible to write several times in a row. (I used Big Decimal for half a year without knowing this ...)

Decimal point calculation using Big Decimal

From here, the calculation handles the decimal point. Since the description of ROUND_UP etc. is deprecated in Java9 or later, please use the description of UP etc. used in this article. BogDecimal allows you to truncate and round off decimal values. Use the setScale method to do this. In the first argument, describe the number of decimal places to control. For example, if the first argument of setscale is 0, it controls to the first decimal place. The description method and usage example are described below.

Rounding method Description method
Rounding HALF_UP
Round up UP
Truncate DOWN

import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
    public static void main(String[] args) {
        //Value definition
        BigDecimal one = BigDecimal.valueOf(1);
        BigDecimal three = BigDecimal.valueOf(3);
        BigDecimal num = new BigDecimal("1.567");


        //A little applied

The variable declaration and assignment on the 3rd line of the value definition are different from the 1st and 2nd lines. Regarding this, even if you use BigDecimal, you may not be able to handle the decimal point perfectly. As a countermeasure against this, when using a decimal point in BigDecimal, it is better to handle it as a String. Although it is a String type, it will calculate as it is.

I made a special description in the second line of the application. I will explain about that. When a recurring decimal occurs in division of the BigDecimal type (0.3333 in this case ...) I get an exception for java.lang.ArithmeticException. As a countermeasure, Big Decimal allows you to write something like the second line of application. With this description, it is possible to write a program without raising an exception.

BigDecimal type conversion

After you finish calculating the decimal point in BigDecimal, you may want to use that value in a primitive type. Therefore, finally, I will describe how to convert from BigDecimal type to int type or double type. Int type and double type are shown as examples.

The type you want to convert Description method
int intValue()
double doubleValue()

import java.math.BigDecimal;
public class Main {
    public static void main(String[] args) {
        //Value definition
        BigDecimal one = BigDecimal.valueOf(1);
        BigDecimal num = new BigDecimal("1.567");
        int a;
        double b;

        //Type conversion
        a = one.intValue();
        b = num.doubleValue();

By writing in this way, it is possible to convert the value calculated by BigDecimal to a primitive type.

in conclusion

This time, I wrote about the basic description of BigDecimal, which is often used to accurately calculate decimal points in Java. There are many other useful methods such as big / small comparison of Big Decimal and exponentiation, so please check them out. If you have an opinion that you would like to know a little more, I may add an article. (I have a desire to write, but it depends on how busy I am ...) If there are any mistakes, strange expressions, or parts that can be described more clearly, it will be my study, so please comment. Thank you for reading this far.

Recommended Posts

To you who suffer from unexpected decimal points in Java
How to get Class from Element in Java
Changes from Java 8 to Java 11
Sum from Java_1 to 100
From Java to Ruby !!
When you want to dynamically replace Annotation in Java8
Migration from Cobol to JAVA
New features from Java7 to Java8
Connect from Java to PostgreSQL
How to store a string from ArrayList to String in Java (Personal)
From Ineffective Java to Effective Java
If you want to change the Java development environment from Eclipse
Multithreaded to fit in [Java] template
[Java] Points to note with Arrays.asList ()
How to learn JAVA in 7 days
Log output to file in Java
Java to be involved from today
From Java to VB.NET-Writing Contrast Memo-
Java, interface to start from beginner
How to use classes in Java?
How to name variables in Java
Try to implement Yubaba in Java
The road from JavaScript to Java
[Java] Conversion from array to List
Do you use Stream in Java?
How to concatenate strings in java
To you who absolutely need backtrace
[Java] Tips and error issues when converting from double to Big Decimal
(Limited to Java 7 or later) I want you to compare objects in Objects.equals
To you who were told "Don't use Stream API" in the field
What is CHECKSTYLE: OFF found in the Java source? Checkstyle to know from
Study Deep Learning from scratch in Java.
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
Try to solve Project Euler in Java
Easy to make Slack Bot in Java
Java reference to understand in the figure
Try to implement n-ary addition in Java
Call Java method from JavaScript executed in Java
Key points for introducing gRPC in Java
OCR in Java (character recognition from images)
Reverse Key from Value in Java Map
Convert from java UTC time to JST time
How to do base conversion in Java
Using JavaScript from Java in Rhino 2021 version
Connect from Java to MySQL using Eclipse
Change List <Optional <T >> to Optional <List <T >> in Java
Convert SVG files to PNG files in Java
How to implement coding conventions in Java
From installing Eclipse to executing Java (PHP)
How to embed Janus Graph in Java
Java Realm is difficult to handle 3 points
Post to Slack from Play Framework 2.8 (Java)
Java: How to send values from Servlet to Servlet
[Java] Flow from source code to execution
How to get the date in java
Get history from Zabbix server in Java
Introduction to monitoring from Java Touching Prometheus
Precautions when migrating from VB6.0 to JAVA
Add footnotes to Word documents in Java