Calculating remainder of two doubles in java

前端 未结 3 1322
独厮守ぢ
独厮守ぢ 2021-01-19 02:04

I have the following code :

Double x = 17.0;
Double y = 0.1;

double remainder = x.doubleValue() % y.doubleValue();

When I run this I get r

3条回答
  •  庸人自扰
    2021-01-19 02:44

    Because of how floating-point numbers are represented.

    If you want exact values, use BigDecimal:

    BigDecimal remainder = BigDecimal.valueOf(x).remainder(BigDecimal.valueOf(y));
    

    Another way to to that is to multiple each value by 10 (or 100, 1000), cast to int, and then use %.

提交回复
热议问题