Skip to content

Commit

Permalink
decimalToPrecision: proper rounding for equidistant digits + test for…
Browse files Browse the repository at this point in the history
… that (ccxt#2407)
  • Loading branch information
xpl committed Mar 30, 2018
1 parent e57cfc7 commit fe16d98
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
4 changes: 2 additions & 2 deletions js/base/functions/number.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,8 @@ const decimalToPrecision = (x, roundingMode

if (i >= (precisionStart + numPrecisionDigits)) {
c = (roundingMode === ROUND)
? ((c > FIVE) ? (NINE + 1) : ZERO) // single-digit rounding
: ZERO // "floor" to zero
? ((c >= FIVE) ? (NINE + 1) : ZERO) // single-digit rounding
: ZERO // "floor" to zero
}
if (c > NINE) { c = ZERO; memo = 1; }
else memo = 0
Expand Down
8 changes: 7 additions & 1 deletion js/test/base/functions/test.number.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ it ('decimalToPrecision: rounding (to N digits after dot)', () => {
equal (decimalToPrecision ('12.3456', ROUND, 4, DECIMAL_PLACES), '12.3456')
equal (decimalToPrecision ('12.3456', ROUND, 3, DECIMAL_PLACES), '12.346')
equal (decimalToPrecision ('12.3456', ROUND, 2, DECIMAL_PLACES), '12.35')
equal (decimalToPrecision ('12.3456', ROUND, 1, DECIMAL_PLACES), '12.3')
equal (decimalToPrecision ('12.3456', ROUND, 1, DECIMAL_PLACES), '12.4') // 12.35 → 12.4 (see the "rounding for equidistant digits" test)
equal (decimalToPrecision ('12.3456', ROUND, 0, DECIMAL_PLACES), '12')
// equal (decimalToPrecision ('12.3456', ROUND, -1, DECIMAL_PLACES), '10') // not yet supported
// equal (decimalToPrecision ('123.456', ROUND, -1, DECIMAL_PLACES), '120') // not yet supported
Expand Down Expand Up @@ -122,4 +122,10 @@ it ('decimalToPrecision: without dot / trailing dot', () => {
equal (decimalToPrecision ('123.', TRUNCATE, 5, DECIMAL_PLACES, PAD_WITH_ZERO), '123.00000')
})

it ('decimalToPrecision: rounding for equidistant digits', () => {

equal (decimalToPrecision ('12.54', ROUND, 1, DECIMAL_PLACES), '12.5')
equal (decimalToPrecision ('12.55', ROUND, 1, DECIMAL_PLACES), '12.6')
})

/* ------------------------------------------------------------------------ */

0 comments on commit fe16d98

Please sign in to comment.