I want to convert enum to string with three digits in C#.
Like this:
enum test : short
{
asdf, qwer, zxcv
}
test t = test.qwer;
string result = t.ToString("%03D") // Is this right?
I want to print 001
In a normal enumeration you can just cast as an integer, then call "ToString" with a format specified. In your case that should look like:
test t = test.qwer;
string result = ((int)t).ToString("000");
That should do it! Good luck.
Related
public static string PadZero(this double number, int decimalPlaces)
{
var requiredFormat = "0." + "".PadRight(decimalPlaces, '0');
var something = $"{number:requiredFormat}";
return number.IsNotZero() ? something: string.Empty;
}
This is a helper function to pad zeros to a double number, user can pass the number of zeros that is required to be padded through decimalPlaces.
Above function fails my unit tests, output received is {requiredFormat} in all test cases.
I have just replaced: var something = $"{number:0.00}"; with a generic variable requiredFormat that can handle any number of zero padding.
There are two problems with your example. The first is that the value of something is not going to produce a string that can be used to format a number. The second is that you are not using something to perform a number format by using string.format.
So first off, the statement:
var something = $"{number:requiredFormat}";
is not going to give you the result that you want, which would be a string that looks something like:
{0:0.0000}
Try changing the code to read:
var something = $"{{0:{requiredFormat}}}";
If you do Console.WriteLine(something) after that statement executes you can inspect the value of something to make sure it is what you are looking for.
After that, change this line:
return number.IsNotZero() ? something: string.Empty;
to read:
return number.IsNotZero() ? string.Format(something, number) : string.Empty;
Even with Interpolated Strings, you have to build the variable format and apply it in two separate steps.
Hope that helps.
I have a string that I would like to format the same way I would a numeric value.
Ex:
int num = 2;
string option = num.ToString("000");
Console.WriteLine(option);
//output
//002
But the only way I can think to format it is to parse it as an int, then apply the ToString("000") method to it.
string option = "2";
option = int.Parse(option).ToString("000");
Is there a better, more direct way to do this?
No, there is no built-in mechanism to "format" a string as if it were a number. Some options:
Use string functions (Pad, Length, Substring) to determine what characters should be added
Parse to a numeric type and use ToString with numeric formatting strings
Use a reqular expression to extract the digits and generate a new string
There's not one "right" answer. Each has risks and benefits in terms of safety (what if the string does not represent a valid integer?), readability, performance, etc.
Would this suit your requirement?
string x = "2";
string formattedX = x.PadLeft(3, '0');
Console.WriteLine(formattedX); //prints 002
I have a numeric id of integer type. I want to add that integer type value to 00000 and concatenate it with string type variable.Assume my integer variable value is 1. After adding the variable it should look like 00001. And I want to concatenate with a string like "Added" and then convert whole thing to a string variable. like this "Added00001". As another example if my integer value is 111 it should look like "Added00111" at the end. Another example integer variable = 1234. Final string should be "Added01234". How to do it...? An example of how to do it.. or Any tutorial how to do such a thing would be really great. Thanks in advance.
You should use the short form format specifier of the ToString method. In the example below, D5 indicates that the integer 111 should be converted to a string with padded zeros to a length of 5 digits, e.g. 00111.
int i = 111;
string s = "Added";
var s = s + i.ToString("D5");
//s = "Added00111"
How do you convert an integer to a string? It works the other way around but not this way.
string message
Int64 message2;
message2 = (Int64)message[0];
If the message is "hello", the output is 104 as a number;
If I do
string message3 = (string)message2;
I get an error saying that you cant convert a long to a string. Why is this. The method .ToString() does not work because it converts just the number to a string so it will still show as "104". Same with Convert.ToString(). How do I make it say "hello" again from 104? In C++ it allows you to cast such methods but not in C#
message[0] gives first letter from string as char, so you're casting char to long, not string to long.
Try casting it back to char again and then concatenate all chars to get entire string.
ToString() is working exactly correctly. Your error is in the conversion to integer.
How exactly do you expect to store a string composed of non-numeric digits in a long? You might be interested in BitConverter, if you want to treat numbers as byte arrays.
If you want to convert a numeric ASCII code to a string, try
((char)value).ToString()
Another alternative approach is using ASCII.GetBytes method as below
string msg1 ="hello";
byte[] ba = System.Text.Encoding.ASCII.GetBytes(msg1);
//ba[0] = 104
//ba[1] = 101
//ba[2] = 108
//ba[3] = 108
//ba[4] = 111
string msg2 =System.Text.Encoding.ASCII.GetString(ba);
//msg2 = "hello"
Try this method:
string message3 = char.ConvertFromUtf32(message2);
104 is the value of "h" not "hello".
There is no integer representation of a string, only of a char. Therefore, as stated by others, 104 is not the value of "hello" (a string) but of 'h' (a char) (see the ASCII chart here).
I can't entirely think of why you'd want to convert a string to an int-array and then back into a string, but the way to do it would be to run through the string and get the int-value of each character and then reconvert the int-values into char-values and concatenate each of them. So something like
string str = "hello"
List<int> N = new List<int>();
//this creates the list of int-values
for(int i=0;i<str.Count;i++)
N.Add((int)str[i]);
//and this joins it all back into a string
string newString = "";
for(int i=0;i<str.Count;i++)
newString += (char)N[i];
Hello everyone as the title say I want to trim the "0." after I do modulo 1 on a double variable
Example:
double Number;
Number = Convert.ToDouble(Console.ReadLine()); //12.777
test = Number % 1; //0.777
I want my output to be: 777
only using math with no
string trims and so...
Thank you all !!
and in c# please
That is just a formatting on the ToString. Take a look at all your options here
How about
.ToString(".###");
Without using any string functions!
while(Math.Round(Number-(int)Number,1)!=1)
{
Number=Number/0.1;
if(Number-(int)Number==0)break;//To cover edge case like 0.1 or 0.9
}
NOTE: Number should be of double type!
If I take your question literally, then you do not want the decimal point either, so .ToString(".###") will not get you what you want, unless you remove the first character (which is string manipulation, and you said you don't want that either).
If you want 777 in a numeric variable (not a string), then you can multiply your result by 1000, though I don't know if you'll always have exactly 3 digits after the decimal or not.
The easiest way really is just to use string manipulation. ToString the result without any formatting, then get the substring starting after the decimal. For example:
var x = (.777d).ToString();
var result = x.SubString(x.IndexOf('.') + 1);
You are certainly looking for this:-
.ToString(".###");
As correctly pointed by Marc in comments you should have everything to be in a string, because if you output that 0.777 as it really is stored internally, you'd get 8 random bytes.
Something like this:-
var num = (.777d).ToString();
var result = num.SubString(num.IndexOf('.') + 1);
The most generic way to do this would be:
using System.Globalization;
var provider = NumberFormatInfo.InvariantInfo;
var output = test.ToString(".###", provider)
.Replace(provider.NumberDecimalSeparator, String.Empty);
You can also set the NumberDecimalSeparator on a custom NumberFormatInfo, but if you set it to empty it will throw the exception "Decimal separator cannot be the empty string."