How To Convert A Binary Fraction Number Into Decimal Fraction Number?
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
Solution 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
Solution 2:
I want to convert a binary fraction number into decimal in JavaScript, like
0.00011001100110011001100
. But I found that there is no radix forparseFloat
as 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 + ')'));
}
Post a Comment for "How To Convert A Binary Fraction Number Into Decimal Fraction Number?"