Multiplying a number with a fraction

Radovan :

I was writing some converters of units using BigDecimals and I ran across a situation where I had to multiply a number with a fraction - periodic number.

For most cases the precision is good enough, but lets say we have an equation like:

BigDecimal.valueOf(90)
          .multiply(BigDecimal.valueOf(10)
                              .divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP))

Normally this would equal 10, however because of rounding, we will get 9.999999...

Is there an elegant way of implementing this without having an if condition detecting when the fraction can be cut?

Andronicus :

The following will work:

BigDecimal.valueOf(90)
    .multiply(BigDecimal.valueOf(10))
    .divide(BigDecimal.valueOf(90), 6, RoundingMode.HALF_UP)

The difference is that here the operations are chained, which allows for resolving such cases. In your solution the division needs to be calculated (where error occurs) and then multiplication, because it's passed as argument.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129781&siteId=1