Handling of java floating point [Note] while reading the reference book

0.7 + 0.1 = 0.8, but if you let the computer calculate it, an error will occur. I will omit the reason why it comes out (** see below **). https://www.php.net/manual/ja/language.types.float.php

The reference book uses ** Big Decimal ** to deal with it.

demojava/demo5/Demo5.java


package demojava.demo5;

import java.math.BigDecimal;

public class Demo5 {
	public static void main(String [] args) {
		double test1 = 0.0;
		test1 = 0.7 + 0.1;
		System.out.println("test1 = " + test1);

		test2();
	}
	public static void test2() {
		BigDecimal val1 = new BigDecimal("0.7");
		BigDecimal val2 = new BigDecimal("0.1");
		BigDecimal val = val1.add(val2);
		System.out.println("test2 = " + val);
	}
}

Execution result

2020-10-10_14-58-25.png

Recommended Posts

Handling of java floating point [Note] while reading the reference book
[Note] Handling of Java decimal point
Output of the book "Introduction to Java"
[Java] Handling of JavaBeans in the method chain
[Note] Java: Measures the speed of string concatenation
2017 reading schedule reference book
Please note the division (division) of java kotlin Int and Int
[Note] Java Output of the sum of odd and even elements
About the operation of Java reading party BOF-held monthly since 1998
Count the number of digits after the decimal point in Java
About the handling of Null
Confront Java Floating Point Error
[Java] Practice of exception handling [Exception]
The story of not knowing the behavior of String by passing Java by reference
The point of addiction when performing basic authentication with Java URLConnection
[Java] Delete the elements of List
[Java version] The story of serialization
Note on the path of request.getRequestDispatcher
Handling of time zones using Java
[Java] Reference / update of Active Directory
Step-by-step understanding of Java exception handling
The origin of Java lambda expressions