Simple question -
How do I convert a string that has been through parseInt back to it' string value?
var myInt = parseInt('J', 36); //19
var myString = myInt.toString(); //returns "19" I would like it to return "J"
Can I do it with longer strings?
var myInt = parseInt("Jon o'reiley", 36); //25511
When converting a string to an int, information of the base the string used is lost. Also any data that was ignored while parsing is lost.
However, just like parseInt toString has a base argument, too:
myInt.toString(36);
Demo from the JS shell:
js> (19).toString(36)
"j"
js> parseInt('abc+foo', 36).toString(36)
"abc"
You can't.
Once an object has been converted to an integer, any other information is lost.
You would have to store J in a seperate object if you wish to access this later.
Related
I have written a script in Javascript, which converts a string to BigInt:
BigInt("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088")
The result is: 28948022309972676171332135370609260321582865398090858033119816311589805691016
I need to find a C# equivalent to this function. I've tried:
Convert.ToInt64("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088") and BigInteger.Parse("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088",NumberStyles.Any)
But both throw the exception: the value could not be parsed.
Does anyone have an idea, what function would work to get the result from the string, like BigInt() in JS?
It should be converted BACK to a string format using the ToString()
Method and you need to pass the parameter in ToString of "R" which
tells it to output the BigInteger as itself.
This is from the documentation:
"In most cases, the ToString method supports 50 decimal digits of precision. That is, if the BigInteger value has more than 50 digits, only the 50 most significant digits are preserved in the output string; all other digits are replaced with zeros. However, BigInteger supports the "R" standard format specifier, which is intended to round-trip numeric values. The string returned by the ToString(String) method with the "R" format string preserves the whole BigInteger value and can then be parsed with the Parse or TryParse method to restore its original value without any loss of data."
You may want to try "R" instead of "N".
See this for more information and an example:
http://msdn.microsoft.com/en-us/library/dd268260.aspx
You need to remove the leading "0x" to parse hex.
private static BigInteger? ParseBigInteger(string input) {
if (input.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
if (BigInteger.TryParse(input.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var bigInt)) {
return bigInt;
}
}
else if (BigInteger.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out var bigInt)) {
return bigInt;
}
return null;
}
//invocation
var bigInt = ParseBigInteger("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088");
// => result: 28948022309972676171332135370609260321582865398090858033119816311589805691016
It corresponds to the long (or Int64), a 64-bit integer
For ref: https://www.educative.io/edpresso/what-is-a-bigint-in-javascript
You need to remove 'x' character from the string and allow hex specifier then it will work:
BigInteger.Parse("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088".Replace("x", string.Empty), NumberStyles.AllowHexSpecifier);
I am trying to understand how parseInt() will work in javascript, my scenarios are
var x = parseInt("123");
console.log(x); // outputs 123
var x = parseInt("1abc");
console.log(x); // outputs 1
var x = parseInt("abc");
console.log(x); // outputs NaN
as of my observation parseInt() converts a string to integer(not really an integer of string like "12sv") when the string begins with number.
but in reality it should return NaN.
From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
"If the first character cannot be converted to a number, parseInt returns NaN."
From Mozilla's docs: "If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point."
So it will parse up to the first invalid character, drop the rest of the string, and return the int it managed to parse until then. If there's no valid characters it will return NaN.
parseInt()->it simply parse the provided value to its equivalent radix conversion,if specified without radix it converts to decimal equivalent.
for coercion purpose, we should avoid using parseInt,we can use Number() function instead.
I tried the following code in a browser console.
var testingVar = 0xffff00;
When I access the variable it returned me the value 16776960 instead of the hexa value. Why does this happen? can't we store hexa value in the variable.
There's no such thing as a "hex value" in Javascript. There are strings and numbers.
0xffff00 is just an alternate syntax for specifying a number. By default the console will print numbers in decimal (base 10), which is why you see 16776960.
You can see a string representation of the number, using a different base with the toString method.
// hex
(0xffff00).toString(16) // "0xffff00"
// decimal
(0xffff00).toString(10) // "16776960"
// octal (for good measure)
(0xffff00).toString(10) // "77777400"
You can use hexadecimals in Javascript.
When you need to convert an octal or hexadecimal string to a number, use the function parseInt(str,base). Consider these examples, first you should define like below
var testingVar = '0xffff00';
And when you need you can call like below:
num = parseInt(testingVar, 16);
This question already has answers here:
Reverse of JSON.stringify?
(8 answers)
Closed 7 years ago.
I need to convert Javascript object to string and then this string back to object.
Objects i get like that:
var Checked = {};
// Hold all checkboxes
$('div.list input[type=radio]:checked, input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Checked[name]) === 'undefined') {
Checked[name] = [];
}
Checked[name].push($el.val());
});
I know how to do this with array by using join and split, but how to be with objects?
Now how to convert this object to string?
How to get back this string to object?
Here you are:
var object = {
"1": [1, 2, {
3: "3"
}]
};
var str = JSON.stringify(object);
console.log(str);
var obj = JSON.parse(str);
console.log(obj["1"][2][3]);
Hope this helps.
The JSON.parse() method parses a string as a JSON object, optionally transforming the value produced by parsing.
Syntax
JSON.parse(text[, reviver])
Parameters
text
The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver Optional
If a function, prescribes how the value originally produced by parsing is transformed, before being returned.
Returns
Returns the Object corresponding to the given JSON text.
Throws
Throws a SyntaxError exception if the string to parse is not valid JSON.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
Syntax
JSON.stringify(value[, replacer[, space]])
Parameters
value
The value to convert to a JSON string.
replacer (Optional)
A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
space (Optional)
A String or Number object that's used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 if it's larger than that. Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.
Source:
JSON.parse()
JSON.stringify()
var obj = { x: 5, y: 6 };
var a = JSON.stringify(obj);
console.log(typeof a);
console.log( a);
var b = $.parseJSON(a);
console.log(typeof b);
console.log( b);
I have a number and this number's base is 32. I need to convert base to 10. How can I do this with javascript ?
var testip="17b3uvp";
var donus=testip.toString(10);
alert(donus)
It is not working.
You use parseInt telling it to use base 32, and then toString:
var testip = "17b3uvp";
var parsed = parseInt(testip, 32);
var donus = parsed.toString(); // 10 is the default, but you can specify it for emphasis/clarity if desired
alert(donus);
The reason your code wasn't working is that you never converted the string to a number. Calling toString on a string just gives you back that string (and String's toString doesn't take any arguments). So first we get a number, parsing the string in the right number base, and then we use Number's toString to create a string in decimal (Number's toString does accept a number base, but 10 is the default).
For base conversion in Javascript using parseInt, use the below format
parseInt(string,base)
base can be any number between 2 and 32.
In your case
var testip="17b3uvp";
var donus=parseInt(testip,10);
alert(donus)
This will alert 17 as result.