C# conversion issue from a generic value to string - c#

I am facing quite an odd issue,....
I have got a code which reads XML and converts each value irrespective of what type it is for example, int, float, double or a String it self to a String value and then stores it into a String variable.
String column = System.Convert.ToString(values.GetValue(rowNum, colNum))
problem I have is, lets say if "values.GetValue(rowNum, colNum)" returns 0.000003825, then when ran, the value that gets converted and stored in "column" is "3.825E-06" which is in scientific notation which I do not really want,
I want "column" to store value 0.000003825 in string format, how do I do that?
thanks

You will need to supply formatting information. Unfortunately, you can't supply formatting information to System.Convert.ToString(). Instead, you must call string.Format() or object.ToString().
For example:
double value = 0.000003825;
string s1 = value.ToString("0.################");
Console.WriteLine(s1);
string s2 = string.Format("{0:0.################}", value);
Console.WriteLine(s2);

Try ToString() to convert it to object

OK, I have fixed this now..
It works a treat irrespective of what the type of value we pass through obj,
thanks.
Object obj = -0.00002357467;
String value = obj.ToString();
String type = obj.GetType().ToString();
if (type.Equals("System.Double")&&value.Contains("E-"))
{
double doubleValue = (double)obj;
value = doubleValue.ToString("0.############################"); //thanks #Matthew Watson
}
Console.WriteLine(value); //prints -0.00002357467

Related

Is it good practice to use ToString() to convert a number directly to a string?

Is it good practice to convert a number to a string directly using ToString()? Like this:
string numStr = 0.ToString();
Or should the number be entered into an int variable first and then use ToString() on that? Like this:
int num = 0;
string numStr = num.ToString();
Its a Good practice to store your numbers in a Variable and then using the ToString() See example at the end
ToString() accepts an over load like ToString(IFormatProvider provider) where you can specify culture-specific format information
Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
The Alternative to ToString() is to use Convert.ToString(Int value) the difference is that Convert also handles null values
var str = Convert.ToString(value);
var str1 = Convert.ToString(value,CultureInfo.InvariantCulture);
Is it good practice to convert a number to a string directly using
ToString()? Like this:
Example
1.ToString(); // Compiles fine
-1.ToString(); // Compile error, note you can surround it with parenthesis to get it to compile
when you say "string a = 0.ToString();"
----------------------^-----here you are already declaring that its a string so saying .ToString(); is redundant

Format numeric string to another numeric string

As I saw in google, there are many implementation for string to an int or decimal... but not to a string.
For example:
decimal d1 = 32221.0210m;
Console.WriteLine(d1.ToString("#,###.00"));
This works but the problem is that I have a string and I don't want to cast it to a numeric.
string str = "32221.0210";
I want it to be:
str = "32,221.02";
Is it possible (without casting)?
For those who ask if is there any reason why not cast: Yes. I am using Infrastructures that receive a string. The infrastructures team don't want to convert it to decimal because they also may recieve another values such as date, etc...
In worse case, it is possible to TryParse decimal, so we know for sure it will work. But for now, we are trying to parse a string to a string as written above.
Thanks in advance :)
A temporary var of type decimal is required:
decimal d;
string str = decimal.TryParse("32221.0210", out d)? string.Format("{0:#,##0.00}", d):string.Empty;

C# How to assign a string to a double

I need help figuring out how to assign a string to a double.
double value = "myString";
I have double value = double.Parse("myString"); but this throws a FormatException.
I have trying to concatenate like this:
string stringValue += doubleValue.toString() + intValue.ToString;
return stringValue;
I have double value = double.Parse("myString"); but this throws a string.Format error.
Yes, that's the behaviour you want in this case. "myString" doesn't have a numerical value, so the correct numerical value to give it, is to throw a formatting error.
double.Parse("1.2") would work or not depending on whether the culture in use was one where 1.2 was represented as "1.2" or as "1,2". double.Parse("1.2", CultureInfo.InvariantCulture) will always return 1.2, because it's specific about which culture to use.
double.TryParse is useful where it's likely for someone to pass an inappropriate string (like "myString") because it returns a boolean representing success or failure, rather than throwing an exception.
You can use TryParse
string x = "1234";
double y;
if(double.TryParse(x, out y))
{
Console.WriteLine("success y = " + y.ToString());
}
else
{
Console.WriteLine(x + " could not be converted to a double");
}
Parse it, assuming myString is a valid double string representation (eg "3.49", "1394.293", "-1.30E3")
double value = double.Parse(myString)
Most (All?) of the normal numerical types have parse methods. Use TryParse if you're unsure if it's valid (Trying to parse "abc" as a number will throw an exception)
#L.B For custom parsing you can define a NumberFormatInfo like this:
var a = new System.Globalization.NumberFormatInfo()
a.NumberDecimalSeparator = ",";
a.NumberGroupSeparator = ".";
double d = Double.Parse("1.000.000,5", a);
You cannot assign a string to a double. It's impossible. A double is a numerical type. A string is not.
If you parse a string that is a double it is possible.
var doubleThing = Double.Parse("9.99");
double.Parse(string);
Can and will through an exception if the format is incorrect. What are you trying to parse?
double.TryParse("1.05", out value);
Will return true or false if the parse succeeds or fails.

formatting string in C#?

I've a predefined string format. For instance '>>>,>>>,>>9.99' this means that the system should display string in this '500,000,000.10'. The format can change based on the users using it. How can I write a common function to display stings on the given format passing
the input value and the format as the parameter using C#
You can use the ToString method with a standard or custom format string
For example:
string format = "{0:000,000,000.00}";
string val = 12.3456;
Console.WriteLine(string.Format(format, value)); // it prints "000,000,123.23"
You can read more about formating values here http://www.csharp-examples.net/string-format-double/
decimal value = 1.2345;
string rounded = value.ToString("d2");
private string sDecimalFormat = "0.00";
decimal d = 120M;
txtText.Text = d.ToString(sDecimalFormat);
You could then have a setting for decimal format eg:
txtText.Text = d.ToString(Settings.DecimalFormat);
String.formate can be used for formating.
Go there if you want examples
http://www.csharp-examples.net/string-format-double/
I think the following might work:
String result = String.Format(fmt.Replace('>', '#').Replace('9', '0'), inpString);
fmt being the format you want to use and inpString being the string entered by the user.
Just replace the > with # and the 9 with 0 and it'll be a valid .Net formatstring.
There is a Format method on String.
String.Format("{0:X}", 10); // prints A (hex 10)
There are several methods to format numbers, date...
I dont seem to understand how you can make 500,000,000.10 from >>>,>>>,>>9.99' but I believe the answer would be
But I assume something you are looking for is: string.Format("500,000,00{0:0.##}", 9.9915)
You can then make a method like
Public string GetString(string Format, object value)
{
return string.Format(Format, value);
}
Something like this?

Why is my enum.Parse method failing?

I'm trying to dynamically set an enum based on the value in a string so far so good I don't know what I've been doing wrong. I have the following code:
public enum TagLabels : long
{
TurnLeft = 0x0000000000000000000030A38DB1,
TurnRight = 0x00000000000000000000307346CC,
LiftApproach = 0x0000000000000000000012107A8D
}
TagLabels IDs;
string someID = "0x0000000000000000000012107A8D";
IDs = (TagLabels)Enum.Parse(typeof(TagLabels), someID ); //<== I get runtime error on this line
I cannot see what's wrong with what I'm doing.
Enum.Parse is intended to convert a string representation of the symbolic name into an enum val, as in Enum.Parse("TurnLeft"). If what you have is a string giving the numeric value, then you should just parse the string as the corresponding integer type and cast it to the Enum val.
IDs = (TagLabels)long.Parse("0x0000000000000000000012107A8D");
IDs = (TagLabels)Convert.ToInt64(someID, 16);
EDIT: You have a string that is in hex format and not a direct number. So, it needs conversion to int first.
If the Enum value exists, you can cast an int value to Enum type.
EDIT2: Changed after Marc's suggestion from Convert.ToInt32 to Convert.ToInt64
SomeID is a string and your enum is a long.
Try using TurnLeft instead of "0x0000000000000000000012107A8D"
Where is the string you're parsing? Aren't you trying to turn a string like "TurnLeft" into TagLabels.TurnLeft?
MSDN

Categories