I want to know the formula of binary 1001100001110110 to -26506 decimal.
I wanted answer is -26506
function changeBinaryToDecimal() {
let binary = "1001100001110110";
let deci = parseInt(binary, 2);
return deci;
}
Related
By using JavaScript to calculate, For Example (in live can be any value)
1000/0.997 = 1003.0090270812437
By using PC calculator to calculate
1000/0.997 = 1003.009027081244 // auto round up last decimal
But if !!!
this is correct and same as window, in this situation no need round up
500/0.997 = 501.5045135406219 // this is correct and same as window calculator
My prefer output is the auto round up value 1003.009027081244
Question: In JavaScript, how to round up the last digit of decimal?
What I have tried:
Math.round(1003.0090270812437) // 1003
const result = Number((1000/0.997).toPrecision(16))
const result = Number((1000 / 0.997).toPrecision(16))
console.log(result)
Maybe you could use string based solution
Convert a decimal number to string, then split it by the ..
Then take a decimal part length substracted by 1, and use it in toFixed on the original number.
You will probably need some additional checks, to see if there is a decimal part of a number
const decimal = 1003.0090270812437;
const text = decimal.toString().split('.')[1];
console.log(decimal.toFixed(text.length - 1)); // 1003.009027081244
Option 1: playing with numbers and decimals
const countDecimals = value => {
let text = value.toString()
if (text.indexOf('e-') > -1) {
let [base, trail] = text.split('e-')
let deg = parseInt(trail, 10)
return deg - 1
}
if (Math.floor(value) !== value) return value.toString().split(".")[1].length - 1 || 0
return 0
}
const round = number => Math.round(number * Math.pow(10, countDecimals(number - 1))) / Math.pow(10, countDecimals(number - 1))
Option 2: playing with strings
let round = number => {
let str = (number).toString()
let [num, dec] = str.split(".")
let leading_zeros = ""
for (const char of dec) {
if (char !== '0') break
leading_zeros += '0'
}
dec = Math.round(parseFloat(dec.substring(0, dec.length - 1) + "." + dec[dec.length - 1])).toString()
return parseFloat(num + "." + leading_zeros + dec)
}
There is no nice javascript way that I know to achieve this. Due to my knowledge this is the way to go:
Math.round(1003.0090270812437*1000000000000)/1000000000000
Edit:
If you do not want to round to a fixed number of decimals, then I would write a little function to count the given decimals before to know your exponent of 10:
var countDecimals = function(value) {
if (Math.floor(value) !== value)
return value.toString().split(".")[1].length || 0;
return 0;
}
var temp = Math.pow(10, countDecimals-1);
Math.round(1003.0090270812437*temp)/temp;
You can just use toFixed(${Amount of decimals you want to show})
Example:
(2321/912).toFixed(1) will show one fraction of the decimal number
(2322/ 1232).toFixed((2322/ 1232).toString().length - 1 ) will round you up the last digit
I have this Function, it rounds all numbers to 8 decimals.
exports.roundDown = function(number, decimals) {
try {
if (!exports.isNumeric(number)) {
return number;
}
decimals = decimals || 8;
if (!exports.isNumeric(decimals)) {
return number;
}
const ret = ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals)*1);
return ret; //(ret < 0.000001) ? 0 : ret;
} catch(e) {
return number;
}
}
The problem I have is that numbers like 0.00000003 are rounded to 0.00000002, instead to send the real number (0.00000003), other numbers work fine.
Any idea how to fix this?
Have you tried the toFixed?
var num = 0.00000002473;
var n = num.toFixed(8);
//n contains 0.00000002
The reason is, that 0.00000003 does not exists. So you can't never round a number to this value. On scanning, it is binary rounded to the nearest possible number. toPrecision(18) shows the number more exact:
(0.00000003).toPrecision(18) // "2.99999999999999973e-8"
And that is why toFixed()returns a string and not a number. In other words: It is impossible to round number to exact 8 decimal digits, except it is binary based number like 0.5, 0.125
I am having an issue with how javascript is dividing and rounding the number.
I have two float , 0.11 and 0.12
I want to calculate the mid of these two numbers and round it to the nearest highest value with 2 decimal price.
For example, if I do this on Calculator
0.11+0.12 / 2 = 0.115, and I need to round it to 0.12 as it is mid or above mid.
If I do this with Javascript, I am not getting an accurate number
Example,
var high = parseFloat(0.12);
var low = parseFloat(0.11);
var mid = (high + low) / 2;
document.getElementById("demo1").innerHTML = mid;
document.getElementById("demo2").innerHTML = mid.toFixed(2);
var another = mid.toFixed(3);
document.getElementById("demo3").innerHTML =another;
var last = Math.floor(another)
document.getElementById("demo4").innerHTML =last;
http://jsfiddle.net/gzqwbp6c/9/
Any input would be appreciated.
As the 0.11499999999999999 shows, the result is very slightly less than 0.115. This is because 0.11 and 0.12 cannot be represented with perfect accuracy using floating-point-numbers.
When you don't want to deal with floating-point-error, it's often easier to work with integers directly. Small integers are represented exactly by floating point numbers.
You can multiply by 100 before, and round, to ensure your numbers are integers, and only divide after you get your final result:
var a = Math.round(100 * parseFloat("0.12")) // 12
var b = Math.round(100 * parseFloat("0.11")) // 11
var mid = (a + b) / 2 // 11.5.
// 0.5 can be represented exactly in floating point for small numbers.
var midRound = (Math.round(mid) / 100).toFixed(2) // "0.12"
Need to multiply (workout on int part, i.e. find mid, and divide to reconvert to origin):
function myMid(high,low, precision){
var precision=2
var convFactor = Math.pow(10,precision);
return
(Math.round((low*convFactor+high*convFactor)/2)/convFactor).toFixed(precision);
}
Float is not precise, you cant rely on that, you'll have unexpected results.
everything *100 to prevent inaccuracies
.toFixed() does the rounding
var a = 0.11;
var b = 0.12;
c = parseFloat((((a*100) + (b*100))/200).toFixed(2));
console.log(c);
How to get precise integer result for multiplication and division operations of huge numbers in JS?
Let's say we have:
var a = 75643564363473453456342378564387956906736546456235342;
var b = 34986098309687982743378379458582778387652482;
Multiplying these numbers gives me a number in scientific "e" notation. How to display the whole precise integer result number?
I've tried using this library
https://github.com/peterolson/BigInteger.js
Readme says:
Note that Javascript numbers larger than 9007199254740992 and
smaller than -9007199254740992 are not precisely represented
numbers and will not produce exact results. If you are dealing with
numbers outside that range, it is better to pass in strings.
But how do you do math with strings?
Use bigInt, as you hinted, you need to use strings instead of numbers to represent them correctly.
bigInt("75643564363473453456342378564387956906736546456235342").multiply("34986098309687982743378379458582778387652482");
I think this question is duplicate of how-to-avoid-scientific-notation-for-large-numbers-in-javascript
This function taken from above link.
function toFixed(x) {
if (Math.abs(x) < 1.0) {
var e = parseInt(x.toString().split('e-')[1]);
if (e) {
x *= Math.pow(10,e-1);
x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
}
} else {
var e = parseInt(x.toString().split('+')[1]);
if (e > 20) {
e -= 20;
x /= Math.pow(10,e);
x += (new Array(e+1)).join('0');
}
}
return x;
}
alert(toFixed(a*b));
I have a 64 bit unsigned integer I need to represent in PostgreSQL. I've broken it down into two 32 bit unsigned integers, high and low. To allow Postgres to accept it, I need to convert high and low to a string representing a signed 64 bit integer.
How can I go about converting two 32 bit unsigned integers to a string representing in decimal a signed 64 bit integer?
I've done exactly this in Javascript in a quick'n'dirty-but-works'n'fast manner at: Int64HighLowToFromString, using 53-bit mantissa double precision arithmetic and 32-bit bit operations, specialized for decimal input/output.
function Int64HiLoToString(hi,lo){
hi>>>=0;lo>>>=0;
var sign="";
if(hi&0x80000000){
sign="-";
lo=(0x100000000-lo)>>>0;
hi=0xffffffff-hi+ +(lo===0);
}
var dhi=~~(hi/0x5af4),dhirem=hi%0x5af4;
var dlo=dhirem*0x100000000+dhi*0xef85c000+lo;
dhi += ~~(dlo/0x5af3107a4000);
dlo%=0x5af3107a4000;
var slo=""+dlo;
if(dhi){
slo="000000000000000000".slice(0,14-slo.length)+dlo;
return sign+dhi+slo;
}else{
return sign+slo;
}
}
Most likely this is what you needed.
I adapted the base conversion code from https://codegolf.stackexchange.com/questions/1620/arbitrary-base-conversion. Mistakes are mine, clevernesses are theirs.
I also had to add a bunch of code to deal with negative numbers (twos complement).
This code is ecmascript5, and will need slight reworking to work in older browsers.
function convert(hi, lo) {
function invertBit(bit) {
return bit == "0" ? "1" : "0";
}
function binaryInvert(binaryString) {
return binaryString.split("").map(invertBit).join("");
}
function binaryIncrement(binaryString) {
var idx = binaryString.lastIndexOf("0");
return binaryString.substring(0, idx) + "1" + binaryInvert(binaryString.substring(idx + 1));
}
function binaryDecrement(binaryString) {
var idx = binaryString.lastIndexOf("1");
return binaryString.substring(0, idx) + binaryInvert(binaryString.substring(idx));
}
function binaryAbs(binaryString) {
if (binaryString[0] === "1") {
return invertBits(binaryDecrement(binaryString));
}
return binaryString;
}
function to32Bits(val) {
var binaryString = val.toString(2);
if (binaryString[0] === "-") {
binaryString = Array(33 - (binaryString.length - 1)).join("1") + binaryInvert(binaryString.substr(1));
return binaryIncrement(binaryString);
}
return Array(33 - binaryString.length).join("0") + binaryString;
}
var fullBinaryNumber = to32Bits(hi) + to32Bits(lo);
var isNegative = fullBinaryNumber[0] === "1";
fullBinaryNumber = binaryAbs(fullBinaryNumber);
var result = "";
while (fullBinaryNumber.length > 0) {
var remainingToConvert = "", resultDigit = 0;
for (var position = 0; position < fullBinaryNumber.length; ++position) {
var currentValue = Number(fullBinaryNumber[position]) + resultDigit * 2;
var remainingDigitToConvert = Math.floor(currentValue / 10);
resultDigit = currentValue % 10;
if (remainingToConvert.length || remainingDigitToConvert) {
remainingToConvert += remainingDigitToConvert;
}
}
fullBinaryNumber = remainingToConvert;
result = resultDigit + result;
}
return (isNegative?"-":"") + result;
}
Examples:
> // largest negative number -2^63 (just the most significant bit set)
> convert(1 << 31, 0)
'-9223372036854775808'
> // largest positive number
> convert(0x7fffffff, 0xffffffff)
'9223372036854775807'
> // -1 is all bits set.
> convert(0xffffffff, 0xffffffff)
'-1'
According to JavaScript can't handle 64-bit integers, can it?, native numbers in Javascript have 53 bits of mantissa, so JS can't deal with 64 bits integers unless using specialized libraries.
Whatever the datatype and implementation limits, I assume you want to compute the Two's complement of the initial 64 bits unsigned number, to convert it from the [0 ... 2^64-1] range into the [-2^63 ... 2^63-1] range.
high is presumably the initial unsigned 64 bits number divided by 2^32, and low is the remainder.
The conversion to a signed 64 bits should go like this:
if high>=2^63 then
s64 = -(2^64-(high*2^32+low))
else
s64 = high*2^32+low;
In a PostgreSQL function, this can be done using the exact-precision numeric type to avoid overflows in intermediate multiplications, and downcast the final result to bigint (signed 64 bits):
create function concat64(bigint, bigint) returns bigint
as $$
select (case when $1>=2147483648
then -(18446744073709551616::numeric-($1*4294967296::numeric+$2))
else $1*4294967296::numeric+$2 end)::bigint;
$$ language sql;
The input arguments have to be bigint (64 bits) because postgres doesn't have unsigned types.
They're assumed to be in the [0..4294967296] range and the output should be in the [-9223372036854775808..9223372036854775807] range.