MikeMcl / decimal.js

An arbitrary-precision Decimal type for JavaScript
http://mikemcl.github.io/decimal.js
MIT License
6.35k stars 480 forks source link

Round Half Up working as expected? #222

Closed matrix4123 closed 1 year ago

matrix4123 commented 1 year ago

I am trying to use the ROUND_HALF_UP method and seeing a strange result in certain scenarios:

let dec = new Decimal(-3.3499999999999996);

let roundBroken = dec.toDecimalPlaces(1, Decimal.ROUND_HALF_UP); 
// Incorrectly rounds to -3.3

let roundToTwoPlaces = dec.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
// Correctly rounds to -3.35

let roundToOnePlace = roundToTwoPlaces.toDecimalPlaces(1, Decimal.ROUND_HALF_UP); 
// Correctly rounds to -3.4

I would expect rounding to a single decimal place would result in -3.4 but is returning -3.3. If I do the rounding twice, I can arrive at -3.4 though.

Any ideas?

MikeMcl commented 1 year ago

The results are as expected.

Why would you expect rounding to a single decimal place to result in -3.4 rather than -3.3?

ROUND_HALF_UP means round away from zero if the rounding digit is 5 or more, and in this case the rounding digit is 4.