Is there a way to convert a String (in hex format) into a Integer? I know of Integer.parseInt(string, 16), but it does not handle the 0x prefix. I'm looking something to the effect of Integer.decode(string) from standard Java.
Thanks in advance.
int convert(String s) {
int base = 10;
if (s.toLowerCase().startsWith("0x")) {
base = 16;
s = s.substring(2);
}
return Integer.parseInt(s, base);
}
Related
How can I convert a string to a double using a method that does not include parse or tryparse? I have the program for converting a string to a long, would it be the same for a double? I am a complete newbie.
Code snippets from OP comment below:
public static bool isLong(string s) {
bool n = true;
int a = 0;
s = s.Trim();
for (a = 0; (a < s.Length); a = a + 1) {
n = n && ((s[a] >= '0') && (s[a] <= '9'));
}
return (n);
}
public static long toLong(string s) {
long ret = 0;
int a;
s = s.Trim();
if (isLong(s)) {
for (a = 0; (a< s.Length); a = a + 1) {
ret = (ret * 10) + (s[i] - '0');
}
} else {
}
return (ret);
}
I think I now understand the question. If so, the answer is yes, sort of.
long is an integer type, so processing one digit at a time is fairly straight forward.
double is a floating decimal type, so you have to figure out a way to deal with the decimal period in the middle.
Is this a class assignment or something where you absolutely must write this code on your own? If not, please consider using the library functions that already exist for this purpose, such as stod: http://www.cplusplus.com/reference/string/stod/
I'm trying to convert a string representing a double from invariant culture to a double in current culture representation, I'm concerned with how to get the new double representation to use the current number decimal separator of Current Culture.
I used the code below for the conversion :
public static double ConvertToDouble(this object inputVal, bool useCurrentCulture = false)
{
string currentSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
string invariantSep = CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator;
if (inputVal.GetType() == typeof(string))
{
if (!currentSep.Equals(invariantSep))
{
inputVal = (inputVal as string).Replace(invariantSep, currentSep);
}
}
if (useCurrentCulture)
return Convert.ToDouble(inputVal, CultureInfo.CurrentCulture);
else
return Convert.ToDouble(inputVal);
}
But the above code always gives me a double with ".", although I use the CurrentCulture for example French supposed to give me a double with comma (",").
Many thanks in advance for any hint.
FreeDev
But the above code always gives me a double with "." as the NumberDecimalSeparator
No, it returns a double. A double is just a number. It doesn't have a NumberDecimalSeparator... only a culture does, and that's only applied when converting to or from strings. Talking about the separator for a double is like talking about whether an int is in decimal or hex - there's no such concept. 0x10 and 16 are the same value, represented by the same bits.
It's not really clear what you're trying to do, but it's crucial to understand the difference between what's present in a textual representation, and what's inherent to the data value itself. You should care about the separator when parsing or formatting - but after you've parsed to a double, that information is gone.
From the comments and your question i guess that you actually want to convert a string to a double with either InvariantCulture or current-culture. This double should then be converted to a string which is formatted by the current-culture datetime-format informations(like NumberDecimalSeparator).
So this method should do two things:
parse string to double
convert double to string
public static string ConvertToFormattedDouble(this string inputVal, IFormatProvider sourceFormatProvider = null, IFormatProvider targetFormatProvider = null)
{
if (sourceFormatProvider == null) sourceFormatProvider = NumberFormatInfo.InvariantInfo;
if (targetFormatProvider == null) targetFormatProvider = NumberFormatInfo.CurrentInfo;
if (sourceFormatProvider == targetFormatProvider)
return inputVal; // or exception?
double d;
bool isConvertable = double.TryParse(inputVal, NumberStyles.Any, sourceFormatProvider, out d);
if (isConvertable)
return d.ToString(targetFormatProvider);
else
return null; // or whatever
}
You can use it in this way:
string input = "1234.567";
string output = input.ConvertToFormattedDouble(); // "1234,567"
Note that i've extended string instead of object. Extensions for object are a bad idea in my opinion. You pollute intellisense with a method that you 'll almost never use (although it applies also to string).
Update:
If you really want to go down this road and use an extension for object that supports any kind of numbers as (boxed) objects or strings you could try this extension:
public static string ConvertToFormattedDouble(this object inputVal, IFormatProvider sourceFormatProvider = null, IFormatProvider targetFormatProvider = null)
{
if (sourceFormatProvider == null) sourceFormatProvider = NumberFormatInfo.InvariantInfo;
if (targetFormatProvider == null) targetFormatProvider = NumberFormatInfo.CurrentInfo;
if (inputVal is string)
{
double d;
bool isConvertable = double.TryParse((string)inputVal, NumberStyles.Any, sourceFormatProvider, out d);
if (isConvertable)
return d.ToString(targetFormatProvider);
else
return null;
}
else if (IsNumber(inputVal))
{
decimal d = Convert.ToDecimal(inputVal, sourceFormatProvider);
return Decimal.ToDouble(d).ToString(targetFormatProvider);
}
else
return null;
}
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
Usage:
object input = 1234.56745765677656578d;
string output = input.ConvertToFormattedDouble(); // "1234,56745765678"
I would like to parse strings like 1 or 32.23 into integers and doubles. How can I do this with Dart?
You can parse a string into an integer with int.parse(). For example:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
Note that int.parse() accepts 0x prefixed strings. Otherwise the input is treated as base-10.
You can parse a string into a double with double.parse(). For example:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse() will throw FormatException if it cannot parse the input.
In Dart 2 int.tryParse is available.
It returns null for invalid inputs instead of throwing. You can use it like this:
int val = int.tryParse(text) ?? defaultValue;
Convert String to Int
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);
Convert String to Double
var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);
Example in DartPad
As per dart 2.6
The optional onError parameter of int.parse is deprecated. Therefore, you should use int.tryParse instead.
Note:
The same applies to double.parse. Therefore, use double.tryParse instead.
/**
* ...
*
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) => ...)`,
* you should use `int.tryParse(string) ?? (...)`.
*
* ...
*/
external static int parse(String source, {int radix, #deprecated int onError(String source)});
The difference is that int.tryParse returns null if the source string is invalid.
/**
* Parse [source] as a, possibly signed, integer literal and return its value.
*
* Like [parse] except that this function returns `null` where a
* similar call to [parse] would throw a [FormatException],
* and the [source] must still not be `null`.
*/
external static int tryParse(String source, {int radix});
So, in your case it should look like:
// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345
// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
print(parsedValue2); // null
//
// handle the error here ...
//
}
void main(){
var x = "4";
int number = int.parse(x);//STRING to INT
var y = "4.6";
double doubleNum = double.parse(y);//STRING to DOUBLE
var z = 55;
String myStr = z.toString();//INT to STRING
}
int.parse() and double.parse() can throw an error when it couldn't parse the String
Above solutions will not work for String like:
String str = '123 km';
So, the answer in a single line, that works in every situation for me will be:
int r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), '')) ?? defaultValue;
or
int? r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), ''));
But be warned that it will not work for the below kind of string
String problemString = 'I am a fraction 123.45';
String moreProblem = '20 and 30 is friend';
If you want to extract double which will work in every kind then use:
double d = double.tryParse(str.replaceAll(RegExp(r'[^0-9\.]'), '')) ?? defaultValue;
or
double? d = double.tryParse(str.replaceAll(RegExp(r'[^0-9\.]'), ''));
This will work for problemString but not for moreProblem.
you can parse string with int.parse('your string value');.
Example:- int num = int.parse('110011'); print(num); // prints 110011 ;
If you don't know whether your type is string or int you can do like this:
int parseInt(dynamic s){
if(s.runtimeType==String) return int.parse(s);
return s as int;
}
For double:
double parseDouble(dynamic s){
if(s.runtimeType==String) return double.parse(s);
return s as double;
}
Therefore you can do parseInt('1') or parseInt(1)
void main(){
String myString ='111';
int data = int.parse(myString);
print(data);
}
String age = stdin.readLineSync()!; // first take the input from user in string form
int.parse(age); // then parse it to integer that's it
You can do this for easy conversion like this
Example Code Here
void main() {
var myInt = int.parse('12345');
var number = myInt.toInt();
print(number); // 12345
print(number.runtimeType); // int
var myDouble = double.parse('123.45');
var double_int = myDouble.toDouble();
print(double_int); // 123.45
print(double_int.runtimeType);
}
Is there any simple method to concatenate '0' before an int variable.
Like:
int i = 2;
// produce
i = someMethod(i);
// output:
i = 02
If you mean "concatenate", then you can define someMethod() as follows:
string someMethod(int i){
return string.Format("{0:d2}", i);
}
The "2" in the string format defines the number of characters in the output.
how to convert string to integer??
for ex:
"5328764",to int base 10
"AB3F3A", to int base 16
any code will be helpfull
Assuming arbitrary base (not 16, 10, 8, 2):
In C (C++), use strtol
return strtol("AB3F3A", NULL, 16);
In Javascript, use parseInt.
return parseInt("AB3F3A", 16);
In Python, use int(string, base).
return int("AB3F3A", 16)
In Java, use Integer.parseInt (thanks Michael.)
return Integer.parseInt("AB3F3A", 16);
In PHP, use base_convert.
return intval(base_convert('AB3F3A', 16, 10));
In Ruby, use to_i
"AB3F3A".to_i(16)
In C#, write one yourself.
in C#, i think it is: Convert.ToInt64(value, base)
and the base must be 2, 8, 10, or 16
9999 is really 9000 + 900 + 90 + 9
So, start at the right hand side of the string, and pick off the numbers one at a time.
Each character number has an ASCII code, which can be translated to the number, and multiplied by the appropriate amount.
Two functions in java, in both directions: "code" parameter represent the numerical system: "01" for base 2, "0123456789" for base 10, "0123456789abcdef" for hexdecimal and so on...
public String convert(long num, String code) {
final int base = code.length();
String text = "";
while (num > 0) {
text = code.charAt((int) (num%base)) + text;
num /= base;
}
return text;
}
public long toLong(String text, String code) {
final long base = code.length();
long num = 0;
long pow = 1;
int len = text.length();
for(int i = 0; i < len; i++) {
num += code.indexOf(text.charAt(len - i - 1)) * pow;
pow *= base;
}
return num;
}
println(convert(9223372036854775807L,"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
println(convert(9223372036854775807L,"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#=-+*/^%$#&()!?.,:;[]"));
println(toLong("Ns8T$87=uh","0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#=-+*/^%$#&()!?.,:;[]"));```
in your example:
toLong("5328764", "0123456789") = 5328764
toLong("AB3F3A", "0123456789ABCDEF") = 11222842