Skip to content

Commit

Permalink
fix(Decimal128): update toString and fromString methods to correctly …
Browse files Browse the repository at this point in the history
…handle the case of too many significant digits
  • Loading branch information
kmahar authored and mbroadst committed Feb 26, 2018
1 parent f6fd5c2 commit 25ed43e
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions lib/bson/decimal128.js
Original file line number Diff line number Diff line change
Expand Up @@ -325,8 +325,6 @@ Decimal128.fromString = function(string) {
}
}

if (significantDigits > 34) invalidErr(string, 'Too many digits to represent accurately');

// Normalization of exponent
// Correct exponent based on radix position, and shift significand as needed
// to represent user input
Expand Down Expand Up @@ -392,7 +390,12 @@ Decimal128.fromString = function(string) {
// If we have seen a radix point, 'string' is 1 longer than we have
// documented with ndigits_read, so inc the position of the first nonzero
// digit and the position that digits are read to.
if (sawRadix && exponent === EXPONENT_MIN) {
if (sawRadix) {
firstNonZero = firstNonZero + 1;
endOfString = endOfString + 1;
}
// if negative, we need to increment again to account for - sign at start.
if (isNegative) {
firstNonZero = firstNonZero + 1;
endOfString = endOfString + 1;
}
Expand Down Expand Up @@ -431,12 +434,8 @@ Decimal128.fromString = function(string) {
);
}
}
} else {
invalidErr(string, 'overflow');
}
}
} else {
invalidErr(string, 'overflow');
}
}

Expand Down Expand Up @@ -722,9 +721,19 @@ Decimal128.prototype.toString = function() {
// has trailing zeros. However, we *cannot* output these trailing zeros,
// because doing so would change the precision of the value, and would
// change stored data if the string converted number is round tripped.

if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
// Scientific format

// if there are too many significant digits, we should just be treating numbers
// as + or - 0 and using the non-scientific exponent (this is for the "invalid
// representation should be treated as 0/-0" spec cases in decimal128-1.json)
if (significand_digits > 34) {
string.push(0);
if (exponent > 0) string.push('E+' + exponent);
else if (exponent < 0) string.push('E' + exponent);
return string.join('');
}

string.push(significand[index++]);
significand_digits = significand_digits - 1;

Expand Down

0 comments on commit 25ed43e

Please sign in to comment.