Home > Java > javaTutorial > body text

A brief discussion on the small deviation problem of Java double multiplication results

高洛峰
Release: 2017-01-23 16:06:58
Original
1583 people have browsed it

Look at the running result of the following piece of code:

public class TestDouble {
 
public static void main(String[] args) {
 
double d =538.8;
 
System.out.println(d*100);
 
}
Copy after login

The output result is surprisingly not 53880, but 53879.99999999999

Solution 1 :

538.8*100 Replace with *10*10 to get the result we want

538.8*10000 Replace with 100*100.

Solution 2:

public class TestDouble {
  public static void main(String[] args) {
   double d =538.8;  
   BigDecimal a1 = new BigDecimal(Double.toString(d));
   BigDecimal b1 = new BigDecimal(Double.toString(100)); 
   BigDecimal result = a1.multiply(b1);// 相乘结果
   System.out.println(result);
   BigDecimal one = new BigDecimal("1");
   double a = result.divide(one,2,BigDecimal.ROUND_HALF_UP).doubleValue();//保留1位数
   System.out.println(a);
  }
}
Copy after login

The above article briefly discusses the small problem of deviation in the result of Java double multiplication, which is all the content shared by the editor. I hope it can To give you a reference, I also hope that everyone will support the PHP Chinese website.

For more articles on the small deviation of the result of Java double multiplication, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!