3

Here is the Example:

For example, suppose we have a float 13.4. In binary, it can be written as: 1101.01100110011001100110011001100110011兮.

Suppose the system stores bits up to 10 decimal places. So 13.4 is stored as: 1101.0110011001 (only 10 decimal places now)

Because of this change, if you convert 1101.0110011001 back to base 10, you get 13.399414. In essence 13.399414 is stored rather than 13.4 in this case!

So given a floating point in base 10, an integer n which represents the number of decimal places as defined above, output the stored value of the float to three decimal places.

So How can i convert using javascript:- input 13.4 and output 13.399

Yasas Gunarathne
  • 833
  • 1
  • 6
  • 19
amit kumar
  • 95
  • 1
  • 10

3 Answers3

0

Going off of the comment by @Jaromanda X

function cut(num, base, len) {
    base = Math.pow(2, base);
    return (parseInt((num * base).toString(2), 2) / base).toFixed(len);
}
0

You can get a number with a desired number of fractional digits by shifting it to the left by that number of places, dropping the remaining digits on the right by flooring it, and shifting it back right. This works in any base - base 2 in your case:

Math.floor(13.4 * 2**10) / 2**10
Math.floor(13.4 * Math.pow(2, 10)) / Math.pow(2, 10)
Math.floor(13.4 * (1<<10)) / (1<<10)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

You can use the Basenumber.js library. Just create an instance in decimal, an parse it to binary:

// Set precision decimals you want
Base.setDecimals(100);

// create instance in decimal
let x = Base(13.4);

// Transform x to binary
let y = x.toBin();

console.log(x.valueOf());
console.log(y.valueOf());

// Transform y to decimal again
let z = y.toDec();

// Since 13.4 has no exact binary representation it would not be accurate
console.log(z.valueOf());

// But you can round the value so get again 13.4
let rounded = z.round(10);   // round 10 decimals

console.log(rounded.valueOf());
<script src='https://cdn.jsdelivr.net/gh/AlexSp3/Basenumber.js@main/BaseNumber.min.js'></script>
AlexSp3
  • 2,201
  • 2
  • 7
  • 24