• Tue 2019.08.20

    This might be of some use to rule out a floating point issue, or cross check a 'C' snippet, by observing the actual mantissa value used at the point of desired rounding:

    by @valderman Feb 2012
    https://stackoverflow.com/questions/9383593/extracting-the-exponent-and-mantissa-of-a-javascript-number

    Adapted from snippet above for the Espruino tests

    function getNumberParts(x) {
        var float = new Float64Array(1),
            bytes = new Uint8Array(float.buffer);
    
        float[0] = x;
    
        var sign = bytes[7] >> 7,
            exponent = ((bytes[7] & 0x7f) << 4 | bytes[6] >> 4) - 0x3ff;
    
        bytes[7] = 0x3f;
        bytes[6] |= 0xf0;
    
        return {
            sign: sign,
            exponent: exponent,
            mantissa: float[0],
        }
    }
    
    tests.forEach(function(x) {
        var parts = getNumberParts(x),
            value = Math.pow(-1, parts.sign) *
                        Math.pow(2, parts.exponent) *
                        parts.mantissa;
    
        console.log( "sign= " + parts.sign + "  exp= " + parts.exponent + "  man= " + parts.mantissa );
        console.log( "Testing:  arg= " + x + "  calc= " + value );
    });
    

    Value under test:

    var tests = [1234.505];
    
    
    sign= 0  exp= 10  man= 1.20557128906
    
    Testing:  arg= 1234.505  calc= 1234.505
    
    =undefined
    > 
    

    Still a bit of work to do with the actual manipulation of the mantissa.

    Also may be used for and related to post:

    Math.round() doesn't follow specification for exact 0.5



    References:

    nice pictorial on bit layout in F.P. register
    https://en.wikipedia.org/wiki/IEEE_754-1985
    https://en.wikipedia.org/wiki/Floating-point_arithmetic

About

Avatar for Robin @Robin started