Skip to content

Commit

Permalink
Fix IEEE754 rounding rule from truncation to roundTiesToEven
Browse files Browse the repository at this point in the history
  • Loading branch information
petamoriken committed Aug 2, 2023
1 parent 2689366 commit 52fe148
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/core-js/internals/ieee754.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
'use strict';
// IEEE754 conversions based on https://github.com/feross/ieee754
var trunc = require("../internals/math-trunc");

var $Array = Array;
var abs = Math.abs;
var pow = Math.pow;
var sign = Math.sign;
var floor = Math.floor;
var log = Math.log;
var LN2 = Math.LN2;

var roundToEven = function (number) {
var truncated = trunc(number);
var delta = abs(number - truncated);
if (delta > 0.5 || delta === 0.5 && truncated % 2 !== 0) {
return truncated + sign(number);
} return truncated;
}

var pack = function (number, mantissaLength, bytes) {
var buffer = $Array(bytes);
var exponentLength = bytes * 8 - mantissaLength - 1;
Expand Down Expand Up @@ -42,10 +53,10 @@ var pack = function (number, mantissaLength, bytes) {
mantissa = 0;
exponent = eMax;
} else if (exponent + eBias >= 1) {
mantissa = (number * c - 1) * pow(2, mantissaLength);
mantissa = roundToEven((number * c - 1) * pow(2, mantissaLength));
exponent = exponent + eBias;
} else {
mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength);
mantissa = roundToEven(number * pow(2, eBias - 1) * pow(2, mantissaLength));
exponent = 0;
}
}
Expand Down

0 comments on commit 52fe148

Please sign in to comment.