在Java中具有双打的模数 [英] Modulus with doubles in Java

查看:122
本文介绍了在Java中具有双打的模数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,您将期望 3.9的结果 - (3.9%0.1) 3.9 (实际上, Google 说我不会疯了),但是当我用Java运行它时,我得到 3.8000000000000003



我知道这是Java存储和进程双重的结果,但是有没有办法解决它? / p>

解决方案

如果需要精确的结果,请使用精确的类型:

  double val = 3.9  - (3.9%0.1); 
System.out.println(val); // 3.8000000000000003

BigDecimal x = new BigDecimal(3.9);
BigDecimal bdVal = x.subtract(x.remainder(new BigDecimal(0.1)));
System.out.println(bdVal); // 3.9

为什么是3.8000 ... 003?因为Java使用FPU来计算结果。 3.9不可能准确存储在IEEE双精度符号中,所以它存储3.89999 ...而不是。而3.8999%0.01给出0.09999 ...因此结果比3.8大一点。


How do you deal with Java's weird behaviour with the modulus operator when using doubles?

For example, you would expect the result of 3.9 - (3.9 % 0.1) to be 3.9 (and indeed, Google says I'm not going crazy), but when I run it in Java I get 3.8000000000000003.

I understand this is a result of how Java stores and processes doubles, but is there a way to work around it?

解决方案

Use a precise type if you need a precise result:

    double val = 3.9 - (3.9 % 0.1);
    System.out.println(val); // 3.8000000000000003

    BigDecimal x = new BigDecimal( "3.9" );
    BigDecimal bdVal = x.subtract( x.remainder( new BigDecimal( "0.1" ) ) );
    System.out.println(bdVal); // 3.9

Why 3.8000...003? Because Java uses the FPU to calculate the result. 3.9 is impossible to store exactly in IEEE double precision notation, so it stores 3.89999... instead. And 3.8999%0.01 gives 0.09999... hence the result is a little bit bigger than 3.8.

这篇关于在Java中具有双打的模数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆