Skip to content

Commit 25ed43e

Browse files
kmaharmbroadst
authored andcommitted
fix(Decimal128): update toString and fromString methods to correctly handle the case of too many significant digits
1 parent f6fd5c2 commit 25ed43e

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

Diff for: lib/bson/decimal128.js

+17-8
Original file line numberDiff line numberDiff line change
@@ -325,8 +325,6 @@ Decimal128.fromString = function(string) {
325325
}
326326
}
327327

328-
if (significantDigits > 34) invalidErr(string, 'Too many digits to represent accurately');
329-
330328
// Normalization of exponent
331329
// Correct exponent based on radix position, and shift significand as needed
332330
// to represent user input
@@ -392,7 +390,12 @@ Decimal128.fromString = function(string) {
392390
// If we have seen a radix point, 'string' is 1 longer than we have
393391
// documented with ndigits_read, so inc the position of the first nonzero
394392
// digit and the position that digits are read to.
395-
if (sawRadix && exponent === EXPONENT_MIN) {
393+
if (sawRadix) {
394+
firstNonZero = firstNonZero + 1;
395+
endOfString = endOfString + 1;
396+
}
397+
// if negative, we need to increment again to account for - sign at start.
398+
if (isNegative) {
396399
firstNonZero = firstNonZero + 1;
397400
endOfString = endOfString + 1;
398401
}
@@ -431,12 +434,8 @@ Decimal128.fromString = function(string) {
431434
);
432435
}
433436
}
434-
} else {
435-
invalidErr(string, 'overflow');
436437
}
437438
}
438-
} else {
439-
invalidErr(string, 'overflow');
440439
}
441440
}
442441

@@ -722,9 +721,19 @@ Decimal128.prototype.toString = function() {
722721
// has trailing zeros. However, we *cannot* output these trailing zeros,
723722
// because doing so would change the precision of the value, and would
724723
// change stored data if the string converted number is round tripped.
725-
726724
if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
727725
// Scientific format
726+
727+
// if there are too many significant digits, we should just be treating numbers
728+
// as + or - 0 and using the non-scientific exponent (this is for the "invalid
729+
// representation should be treated as 0/-0" spec cases in decimal128-1.json)
730+
if (significand_digits > 34) {
731+
string.push(0);
732+
if (exponent > 0) string.push('E+' + exponent);
733+
else if (exponent < 0) string.push('E' + exponent);
734+
return string.join('');
735+
}
736+
728737
string.push(significand[index++]);
729738
significand_digits = significand_digits - 1;
730739

0 commit comments

Comments
 (0)