josdejong / josdejong/mathjs

round behavior inconsistent among numeric types

Open
#3,367 0 comments 0 reactions 0 assignees View on GitHub
bug category:numerical design decision
Dominant language
JavaScript
Stars
15.1k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
Rounding half-integers always involves some choice, but this aspect is (a) not addressed in mathjs documentation and (b) performed inconsistently for different numeric types.

**To Reproduce**
```
import math from 'mathjs'
math.round('-3.5') // -4
math.round(math.fraction(-7/2)) // -3/1
```

**Discussion**
There are numerous rules for rounding halves. Ideally, mathjs would pick one as a default and apply it consistently across numeric types, and allow an options object supporting the existing optional arguments `n` giving the precision in digits (say under the key 'precision') and `unit` giving the desired output unit when the input is a Unit (say under the key 'unit') as well as a new option 'half' which could be any of:

- ceil: round halves up (apparent behavior for Fraction at the moment)
- floor: round halves down
- fix: round halves toward zero
- away: round halves away from zero (We don't have a mathjs function for rounding _all_ non-integers away from 0 as far as I know, but it is a common recommended rule "in the wild" for rounding halves, not to mention the apparent behavior for `number` at the moment.)
- even: round toward the nearest even number (Aka "banker's rounding" because on average it is fair to parties in repeated transactions; half the time you lose 50 cents, half the time you gain it.)
- odd: round toward the nearest odd number (I don't think anyone ever uses this so we would only be supplying it for exhaustiveness. I would consider this one optional.)

If a design decision is reached here, I am happy to supply a PR.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.