How to convert binary fraction to decimal

前端 未结 6 1174
北荒
北荒 2020-12-10 10:52

Javascript has the function parseInt() which can help convert integer in a binary form into its decimal equivalent:

parseInt(\"101\", 2) // 5
         


        
6条回答
  •  无人及你
    2020-12-10 11:15

    TL;DR:

    const convert = (s, b) => (+((s = s.toString().trim().split("."))[0][0] !== "-") || -1) * ((parseInt(s[0].replace("-", ""), (b = +b || 2))) + (s[1].split("").reduceRight((n, d) => (n + parseInt(d, b)) / b, 0)));
    

    Nina Scholz has a nice example, but it doesn't work with negative numbers (plus other issues).
    So, this is an improved one:

    /**
     * @param {string} input
     * @param {number} [base]
     * @returns {number}
     */
    function convert(input, base = 2) {
        const [ integerRaw, decimalRaw = "" ] = input.toString().trim().split(".");
    
        const integer = parseInt(integerRaw.replace("-", ""), base);
        const decimal = decimalRaw.split("").reduceRight((sum, num) => (sum + parseInt(num, base)) / base, 0);
    
        return (integerRaw.startsWith("-") ? -1 : 1) * (integer + decimal);
    }
    
    convert("1100.0011"); // 12.1875
    convert("-1100.0011"); // -12.1875
    convert("-Z.ZZZ", 36); // -35.99997856652949
    

    As I know, JavaScript doesn't provide such built-in functionality.

提交回复
热议问题