How to convert binary fraction to decimal

前端 未结 6 1163
北荒
北荒 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:19

    But I'm wondering whether there is anything standard already.

    No according my knowledge

    I think you need to create your own function:

      function toDecimal(string, radix) {
        radix = radix || 2;
        var s = string.split('.');
        var decimal = parseInt(s[0], radix);
    
        if(s.length > 1){
           var fract = s[1].split('');
    
           for(var i = 0, div = radix; i < fract.length; i++, div = div * radix) {
              decimal = decimal + fract[i] / div;
           }
        }
        return decimal;
      }
    

提交回复
热议问题