I want to remove the characters after 2 decimal values. while I'm formatting not getting any changes in the value. I don't want convert it to double and then string due to performance issue may arise.
data type is Float in the database
value -172.209
Exp op - 172.20
code
string max_demand = dt_max_demand.Rows[0][0].ToString();
max_demand= String.Format("{0:0.0#}", max_demand);
You could search for the last '.' character in your string and then cut it after 2 more chars but it would be way more efficient and easier to format it using $"{dt_max_demand.Rows[0][0]:F2}", assuming dt_max_demand.Rows[0][0] has a numeric type before you cast it to a string.
string max_demand = $"{dt_max_demand.Rows[0][0]:F2}";
Related
I have this tag in a XML
<seguroTotalReais>000000000037103</seguroTotalReais>
I need to set this value like a decimal with 2 places for example 371,03.
Is there a way to do this without manipuling string directly?
You have a couple of options, personally I would not do string operations on this. If you are looking to shift the decimal 2 places i would convert and then divide by 100. This will also give you some validation on whether its a numeric value or not.
string dec = "000000000037103";
// I did a string replace for swapping the dot to a comma.
Console.WriteLine((Convert.ToDouble(dec)/100).ToString("0.##").Replace(".",","));
You can also utilize Culture info to affect how your numbers are displayed as some culture info's utilize the comma as the decimal separator.
I have what I think is an easy problem. For some reason the following code generates the exception, "String must be exactly one character long".
int n = 0;
foreach (char letter in charMsg)
{
// Get the integral value of the character.
int value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
string hexOutput = String.Format("{0:X}", value);
//Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
charMsg[n] = Convert.ToChar(hexOutput);
n++;
}
The exception occurs at the charMsg[n] = Convert.ToChar(hexOutput); line. Why does it happen? When I check the values of CharMsg it seems to contain all of them properly, yet still throws an error at me.
UPDATE: I've solved this problem, it was my mistake. Sorry for bothering you.
OK, this was a really stupid mistake on my part. Point is, with my problem I'm not even supposed to do this as hex values clearly won't help me in any way.
What I am trying to do it to encrypt a message in an image. I've already encrypted the length of said message in last digits on each color channel of first pixel. Now I'm trying to put the very message in there. I lookt here: http://en.wikipedia.org/wiki/ASCII and said to myself without thinking that usung hexes would be a good idea. Can't belive I thought that.
Convert.ToChar( string s ), per the documentation requires a single character string, otherwise it throws a FormatException as you've noted. It is a rough, though more restrictive, equivalent of
public char string2char( string s )
{
return s[0] ;
}
Your code does the following:
Iterates over all the characters in some enumrable collection of characters.
For each such character, it...
Converts the char to an int. Hint: a char is an integral type: its an unsigned 16-bit integral value.
converts that value to a string containing a hex representation of the character in question. For most characters, that string will be at least two character in length: for instance, converting the space character (' ', 0x20) this way will give you the string "20".
You then try to convert that back to a char and replace the current item being iterated over. This is where your exception is thrown. One thing you should note here is that altering a collection being enumerated is likely to cause the enumerator to throw an exception.
What exactly are you trying to accomplish here. For instance, given a charMsg that consist of 3 characters, 'a', 'b' and 'c', what should happen. A clear problem statement helps us to help you.
Since printable unicode characters can be anywhere in range from 0x0000 to 0xFFFF, your hexOutput variable can hold more than one character - this is why error is thrown.
Convert.ToChar(string) would always check length a of string, and if it is not equal to 1 - it would throw. So it would not convert string 0x30 to hexadecimal number, and then to ascii representation, symbol 0.
Can you elaborate on what you are trying to archieve ?
Your hexOutput is a string, and I'm assuming charMsg is a character array. Suppose the first element in charMsg is 'p', or hex value 70. The documentation for Convert.ToChar(string) says it'll use just the first character of the string ('7'), but it's wrong. It'll throw this error. You can test this with a static example, like charMsg[n] = Convert.ToChar("70");. You'll get the same error.
Are you trying to replace characters with hex values? If so, you might try using a StringBuilder object instead of your array assignments.
Convert.ToChar(string) if it is empty string lead this error. instead use cchar()
We have an import service for stores into our database. The latitude and longitude columns are not currently being formatted on import and have resulted in invalid values being inserted into our db. I therefore need to format any lat/long to have 3 places before the decimal and up to 6 after which I thought would be Format("###.######") but it doesn't seem to work. Input values such as 38.921322 or -12.235 have not seemed to conform to the formatting provided. Could anyone a bit more experienced in the area of C# string formatting shed light on how to achieve this? Thank you in advance.
Have you tried String.Format("{0:000.000000}", value);?
Console.WriteLine("{0:000.000000}", 123);
Outputs: 123.000000
Use "0" instead of "#". From MSDN:
0 Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
# Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.
I have a double, and I want to change it to a string, like this:
double value;
string myString = value.toString();
When value is a number with less than 4 digits after the point, it works fine.
For example,
if value is 0, myString will be 0.
if value is 0.01, myString will be 0.01.
But in cases when value has 4 or more digits after the point, myString is created with a floating point (for example, 1E-05).
I want myString to be created in a format of 0.0000000X for any number of digits after the point, and never use the 1E-0X method.
I also want to keep myString as short as possible, for exmaple when the value is 0, i want myString to be 0 (and not 0.000000).
How can I do it?
Thanks
I'm not sure there's a standard numeric format string that will do what you want, but you can use a custom one:
double d = 0.0000003;
Console.WriteLine(d.ToString("0.#################"));
I don't believe that will handle values which end up having significant digits beyond what I've specified though. Extending the number of hashes doesn't help with numbers such as 3e-20, for example. Is that a problem for you?
Note that because you're using double rather than decimal, you may get a surprise in some cases after arithmetic... If you're trying to preserve a value where the exact digits are really important, you should probably be using decimal instead.
Use one of the double.ToString overloads that accept a format string as an argument.
Check the information on standard numeric format strings and custom numeric format strings to learn about specifying the desired formatting.
the msdn page for Double.ToString() explains it pretty well.
string myString = value.ToString("R");
would do the job.
I am trying to format a double in C# such that it uses the thousand separator, and adds digits upto 4 decimal places.
This is straight forward except that I dont want to have the decimal point if it is an integer. Is there a way to do this using the custom numeric format strings rather than an if statement of tenary operator?
Currently I have:
string output = dbl.ToString(dbl == (int)dbl ? "#,##0" : "#,##0.####");
Thanks
I believe your second format string of "#,##0.##" should be exactly what you want -- the # format character is a placeholder that will NOT display zeros.
If you had "#,###.00" then you would get trailing zeros.
test code:
double d = 45.00;
Console.Writeline(d.ToString("#,##0.##"));
Gives output of "45". Setting d to 45.45 gives output "45.45", which sounds like what you're after.
So you had the answer after all! ;)
Incidentally, there's a handy cheat-sheet for format strings (amongst other handy cheat-sheets) at http://john-sheehan.com/blog/net-cheat-sheets/
No, there is not any built-in format string for this. Your current solution is the best way to accomplish this.
MSDN lists both the standard numeric format strings and custom numeric format strings, so you should be able to see for yourself that none directly matches your needs.