I want to convert a binary fraction number into decimal in JavaScript, like 0.00011001100110011001100. But I found that there is no radix for parseFloat as for parseInt, So how can I do that?
            Asked
            
        
        
            Active
            
        
            Viewed 170 times
        
    1
            
            
         
    
    
        L_K
        
- 2,838
- 2
- 16
- 36
2 Answers
1
            There may well be a better way, but here's a generic function with pick your own radix goodness
var binFraction = function(s, radix) {
    radix = radix || 2;
    var t = s.split('.');
    var answer = parseInt(t[0], radix);
    var d = t[1].split('');
    for(var i = 0, div = radix; i < d.length; i++, div = div * radix) {
        answer = answer + d[i] / div;
    }
    return answer;
}
No error checking done on the input, or the radix, but it seems to work OK
 
    
    
        Jaromanda X
        
- 53,868
- 5
- 73
- 87
0
            
            
        I want to convert a binary fraction number into decimal in JavaScript, like
0.00011001100110011001100. But I found that there is no radix forparseFloatas forparseInt, So how can I do that?
We can build a parseFloatRadix() function like this:
function parseFloatRadix(num, radix) {
  return parseInt(num.replace('.', ''), radix) /
    Math.pow(radix, (num.split('.')[1] || '').length)
}
This stackowerflow answer provides more detail. Demo code below.
function parseFloatRadix(num, radix) {
  return parseInt(num.replace('.', ''), radix) /
      Math.pow(radix, (num.split('.')[1] || '').length)
}
test('0.00011001100110011001100', 2, 0.09999990463256836);
function test(num, radix, expected){
  let result = parseFloatRadix(num, radix);
  console.log(num + ' (base ' + radix +') --> ' + result + 
    (result === expected ? ' (OK)' : ' (Expected ' + expected + ')'));
} 
    
    
        Tomas Langkaas
        
- 4,551
- 2
- 19
- 34