I've searched these forums and have found nothing. What I'm trying to find is a function in PHP that will convert a binary representation into a regular integer. parseInt seems to do the trick in JavaScript, but I need a serverside equivalent for the specific program I am creating. Anyone have thoughts?
i.e. parseInt(110100101); in JavaScript returns 421. I need a function that returns the same number with that binary.
bindec will do what you are looking for. You just need to make sure that you are passing it as a string, so if you have as an int, just cast it to a string first
$newInt = bindec( (string) $binaryInt );
Otherwise if its already a string you dont need to cast it to one and can just pass it in:
$newInt = bindec( $binaryString );
Related
i was working with buffer in JavaScript. I want to write the buffer with first five digit of provided input. But instead of returning 23917 it return 2.391.Can someone explain why it does that?
Thank you so much in advance.
var number=23917397219379217392781;
var buffer=new Buffer.alloc(5,number.toString());
console.log(buffer.toString());
That's because for large numbers, toString() returns a scientific-notation string representation of the number.
In your case, number.toString() is '2.3917397219379218e+22'.
To get around this, implement your own numberToString method, and use that to get a non-scientific-notation string like '23917397219379217392781'
I use the new Parse Server, and in the cloud part which is using Javascript I want to check if an integer is specified by a user, in other words I want to check if the Int is null or not. I can do it for strings, but as I see from comments, an int can not be null. Bu I do not want to change all ints in my code to integers. I try the code below, but it is not working, how can I check if there is a number specified by the user or if it is empty?
if (!req.object.get('number'))
Your code should work as long as number isn't zero. To handle that case as well, simply do a type check like this:
if (typeof req.object.get('number') !== 'number').
It seems like you are confusing java and javascript. Javascript does not have ints or integers, only numbers. Javascript variables do not have types and all variables can be null and undefined.
In my code, the value of a particular var can originate from any one of a number of different json sources. For some of those sources, the json element concerned will be a string (e.g. "temp": "10.2"), while for other sources the json element will already be a float (e.g. "temp": 10.2).
Does it do any harm (is anything likely to break) if I just pass the json element (from whatever source) through a parseFloat(), even if it's already a float? It seems to work; I'm just thinking about good/bad practice and possible breakage in future or on a different platform.
Thanks.
You should be able to call parseFloat() on a float or a string without any problems. If it is a float already, it's converted to a string first, and then to a float again, so it's a little less efficient, but it shouldn't matter too much.
You should still check the result for NaN, in case there's something unexpected in the data.
The most appropriate method to convert any datatype to a number is to use the Number function:
In a non-constructor context (i.e., without the new operator),
Number can be used to perform a type conversion.
Number("1234") // 1234
Number(1234) // 1234
This method differs from parseFloat in these ways at least:
Number function does not perform "double-conversion" if the input is already a number (ref)
Parse float converts the input to a string then extracts the number (ref)
Number function returns common sense values for most datatypes e.g. Number(true) yields 1
Parse float uses the string value of input so parseFloat(true) tries to parse number from "true" and yields NaN
Number function fails when input string is an invalid number e.g. Number("123abc") yields NaN
Parse float tries to parse as much of a number as possible e.g. parseFloat("123abc") yields 123
If you are sure the value is always a valid number, you should use Number(stringOrNumber).
If you need some additional safety using parseFloat() you could also write your own function which is also performance optimized:
function toFloat(value) {
return typeof value === 'number' ? value : parseFloat(value);
}
I also created a jsPerf test case that shows the performance is >30% better than the plain parseFloat() for a 1:1 ratio between strings and numbers as input values.
Nope there is no problem with passing a number to it
MDN says as long as it can be converted to a number, nothing breaking should happen.
If the first character cannot be converted to a number, parseFloat returns NaN.
As an alternative, you could use the unary operator + which does basically the same thing as parseFloat and also returns NaN if it didn't work.
For instance:
var myFloat = +('10.5');
var myOtherFloat = parseFloat('10.5', 10);
var alreadyAFloat = parseFloat(10.5, 10);
console.log(myFloat === myOtherFloat && myOtherFloat === alreadyAFloat); // true
Wether it's a float or a String using parseFloat() is much safer to avoid all kind of errors.
As you said it will always work, but if you enforce it to be a float you will avoid getting any Exception.
For Example:
Both parseFloat('10.2', 10) and parseFloat(10.2, 10) will work
perfectly and will give you the same result which is 10.2.
Personally I can't see this being a problem what so ever, to be honest I would always use the parsefloat() for one reason, and that is safety. You can never be to sure what may happen, so always predict the worse :D
I am trying to pass a big int to a function from an onclick event in HTML. The ints are always very long, and I cannot seem to pass it to my function without rounding. I have tried some bigInt libraries to the same end, though I would much rather prefer simple string casting.
My js function:
function initBuy(id){
console.log(id.toString());
}
and my HTML event:
<dt></dt><dd><a id="buy" onclick="initBuy(String(' + all_data[index].listing_id + '))" class="btn btn-success">Buy This Item</a></dd>
An example of a passed int:
13934317650292905813
and the result of clicking the button:
"13934317650292906000"
The passed int looks fine when I write it to an elements' text. When I pass it to a function, however, it's rounding it.
From the post here the maximum value an integer in Javascript could take is 9007199254740992
Your number 13934317650292905813 is far bigger than that.
From this post here you can use BigInteger.js to accommodate big integers
You say in your (ambiguous) question:
'The passed int looks fine when I write it to an elements' text. When I pass it to a function, however, it's rounding it.'
and in your comment:
If I set all_data[index].listing_id to an elements text, it works.
That means you are already getting the 'integer' as text-string in JSON.
Nothing in your current question converts the string to a number (I tested it).
As soon as the string would be converted to a number it would overflow IEEE 754's max accuracy of 2^53=9007199254740992.
Note that: initBuy(String(' + all_data[index].listing_id + '))
will return the string + all_data[index].listing_id + (as it should).
Passing the string '13934317650292905813' to your initBuy function also returns string '13934317650292905813' (as it should).
In other words, I can not reproduce your problem using the code you have supplied.
I assume you have simplified your initBuy function for this question (you'd have to post the original one for further examination, preferably together with an excerpt of a relevant part of the raw JSON string).
I assume you might accidentally convert the string to a number (probably using a +) inside that function!
If you do this...
var parsed = JSON.parse('{"myNum":0.0}') ;
Then when you look at parsed.myNum, you just get 0. (Fair enough.)
If you do parsed.myNum.toString(), you get "0".
Basically, I'm looking for a way to turn this into the string "0.0".
Obviously, in real life I don't control the JSON input, I get the JSON from a web service... I want to parse the JSON using the browser's JSON parser, and to be able to recognise the difference between the number values 0 and 0.0.
Is there any way to do this, short of manually reading the JSON string? That's not really possible in this case, I need to use the browser's native JSON parser, for speed. (This is for a Chrome extension by the way; no need to worry about it working in other browsers.)
There's no way to get the number of digits from JSON.parse or eval. Even if IBM's decimal proposal had been adopted by the EcmaScript committee, the number is still going to be parsed to an IEEE 754 float.
Take a look a http://code.google.com/p/json-sans-eval/source/browse/trunk/src/json_sans_eval.js for a simple JSON parser that you can modify to keep precision info.
If 0.0 is not enclosed in quotes in your JSON (i.e. it's a number and not a string), then there's no way to distinguish it from 0, unless you write your own JSON parser.
... parsed.myNum.toFixed( 1 ) ...
where 1 is number of decimal places
Edit: parsed.myNum is number, parsed.myNym.toFixed( 1 ) would be string
Edit2: in this case you need to pass value as string {"myNum":'0.0'} and parsed when calculations is needed or detect decimal separator, parsed number, and use decimal separator position when string is needed
It shouldn't matter, 00000.00000 is 0 if you try JSON.parse('{"myNum":0.00001}') you'll see a value of { myNum=0.0001 } If you really need it to hold the decimal you'll need to keep it a string JSON.parse('{"myNum":"0.0"}')