← Back to all posts

## Javascript

I need to shorten it but not by uglyfying it, just a better algorithm.
It's supposed to turn a binary string (e.g: "010.00101") and get the accuracy (number of signifincant digits, ie: 010.00101 => 1000101 = 7 digits), then the exponent (ie: 010.00101 => ≈1.001 x 2^1), and finally if the digits after the dot end in something like 000001, i'd like to chop them off the accuracy as it's close enough.

``````value = value.toString(2);
var accuracy = value.replace(".", "").length - 1;
accuracy -= (val.match(/(1[01]*?\.[01]*?|0\.[01]*?1[01]*?)(0{4,}[01]*1)/)||[0,0 ,""])[2].length;
var exponent = val.indexOf(".") - 1;
if(!val.includes("1")){
exponent = -Infinity
}
if(val.split(".")[0]=="0" && exponent!=-Infinity){
exponent = -(val.split(".")[1].indexOf("1")-1)
}``````

EDIT: updated regex

EDIT: I've scrapped this algorithm but if u find answer it'll still help! (You will still get 5 cycles)

Answered by xxpertHacker (863) [earned 5 cycles]
hotnewtop
xxpertHacker (863)

Untested:

``````value = value.toString(2);

const accuracy = value.replace(`.`, ``).length - 1 - (/\d*?\.\d*?0000\d*1/.exec(value) || [,,``])[2].length;

let exponent = value.indexOf(`.`) - 1;

exponent = !value.includes(`1`)
? -Infinity
: (value.split(`.`)[0] === ` ` && exponent !== -Infinity
? -value.split(`.`)[1].indexOf(`1`) + 1
: exponent);``````

Update: try

``````exponent =
value.split(`.`)[0] === ` ` && !value.includes(`1`)
? -value.split(`.`)[1].indexOf(`1`) + 1
: exponent;``````
xxpertHacker (863)

Btw, ping me for stuff like this if you ever post another question, any language. Especially for regular expressions. I'm a human compiler.

xxpertHacker (863)

Did it even work? I wrote `untested`. That was theoretical.

MatReiner (124)

@StudentFires im closing this post. Hard work, you earned the 5 cycles.

xxpertHacker (863)

As a regexpert, I can say I'm improved upon your regex: `\d*?\.\d*?0000\d*1`.
`\d*\.\d*?0000\d*1` might work too.
I still recommend using `%` or a function from `Math` to remove the decimal.
Gimme an upvote, I'm desperate

AphixDev (217)

If I were you, I would see if there is a better formatted version of this. looks like some ansi escape codes...

MatReiner (124)

@nt998302 because of stupid regex