Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

javascript - How to convert binary fraction to decimal

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

parseInt("101", 2) // 5

However, I need to convert binary fraction to its decimal equivalent, like:

0.101 = 0.625

I can write my own function that would calculate the result like the following:

1 * Math.pow(2, -1) + 0*Math.pow(2, -2) + 1*Math.pow(2, -3) // 0.625

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This question asks whether there is some JavaScript standard for parsing binary floating-point numbers, as if parseFloat() could have taken a second radix parameter to parse the binary number 0.101 like this: parseFloat('0.101', 2).

While there is no such standard, there is an easy and direct way to solve this.

If we represent the binary number 0.101 as a binary fraction, it is easily converted to a decimal fraction:

0.1012 = 1012/10002 = (5/8)10 = 0.625

The following one-line expression translates this to JavaScript. Here, num could be any type of binary number (represented as a string), including negative numbers:

parseInt(num.replace('.', ''), 2) / Math.pow(2, (num.split('.')[1] || '').length)

The solution is easily adapted to floating-point numbers in any base between 2 and 36, and we can wrap it in our own parseFloatRadix() function:

function parseFloatRadix(num, radix) {
  return parseInt(num.replace('.', ''), radix) /
    Math.pow(radix, (num.split('.')[1] || '').length)
}

test('0.101',  2, 0.625);
test('0.011',  2, 0.375);
test('0.0011', 2, 0.1875);
test('-011',   2, -3);
test('011',    2,  3);
test('-1100.0011', 2, -12.1875);
test('1100.0011',  2,  12.1875);
test('0.00011001100110011001100', 2, 0.09999990463256836);

test('ABC',     16, 2748);
test('-0.DEF',  16, -0.870849609375);
test('ABC.DEF', 16, 2748.870849609375);

test('-102.201', 3, -11.703703703703704);
test('-Z.ZZZ',  36, -35.99997856652949);

function test(num, radix, expected){
  let result = parseFloatRadix(num, radix);
  console.log(num + ' (base ' + radix +') --> ' + result + 
    (result === expected ? ' (OK)' : ' (Expected ' + expected + ')'));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...