Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I need to convert a string to decimal with specific format in C#. This string can be in different formats. For example it can be: 20 or 20.5.
I need it to convert to xx.xxx. Is there is a method to do this?
C# decimal values are binary. They do not have a human-readable format and can NEVER have a human-readable format. Anything you see otherwise is a convenience provided by the debugger or other tooling. If you need a decimal formatted in a certain way, what you really need is a string.
That said, the decimal type is a good intermediary to be sure you get the correct desired string output: first Parse() the original string value to a decimal, then convert from a decimal to the final formatted string result using the decimal's ToString() method.
Finally, it's important to understand cultural and internationalization issues mean converting between strings and true numeric values is far more error-prone and slow than we'd like to believe. It's something to avoid. Therefore the best strategy is usually parsing a value into an unformatted decimal as quickly as possible, and then keeping it there as long as possible — until the last possible moment before you need to format it for output.
You can specify the format like the below:
string t = "2020.5";
var d = decimal.Parse(t).ToString("00.000");
If your string contains any special character you need to sanitize it before you parse it. E.g. if the string contains space you can replace it with empty char like this:
t = t.Replace(" ", "");
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want to convert a set of string into another meaningful string using c#
For Example
I want to convert the string "Aneesh" into "Syam"(The Name should Always convert into same Dummy name Always)
The Dummy values should be consistent based on an input seed
The Random Class of C# uses Seeds, if u would for example when you want to convert Aneesh you would put Aneesh as the input seed (just convert it into int with a method you like or set a reference int to it) and the Random Class if im not wrong should always do the same randoms then. Just convert those via int -> char -> string and you got your random word.
another way of doing it obviously would be setting up a consistent pair of strings, and just when converting taking the other one.
But i dont understand what you mean Aneesh into Syam, because u first said you want another meaningfull string which is consistent, and in the other hand you want string a swapped with string b, these are different things and can be acomplished in diff. ways
The simpliest solution that comes to my mind is to add 1 on every character:
var result = input.ToDictionary(x => x, x => new string(x.Select(y => y + 1).ToArray());
This produces different values for different keys, but is highly deterministic and unabmigious.
[
["Aneesh", "Boffti"],
["Head", "Ifbe"],
["Hand", "Iboe"]
]
Maybe you also need some check that character do not "overflow", that is z + 1 results in {, but instead of A.
If you need a bit more randomness you can of course add any different number than 1 and add that to every character.
Another appraoch which is not de-anonymizable as it produces compeleteley unrelated data is to just randomize based on the index within your input-list:
var result = input.Select((x, i) => $"Dummy{ i }");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
In c# when adding two decimals the program will automatically get rid of the number 0 after the decimal places.
For example adding 0.50 to 1.20 will produce the answer of 1.7 and this is annoying because i need to display this answer in terms of money.
Is there a way to prevent this?
If you want to display your Decimal with two decimal places, please use :
myDecimal.ToString("N2");
You may want to take a look at Standard Numeric Format Strings for more information.
decimal d = 0.50m;
decimal d1 = 1.20m;
Console.Write(d+d1);
Please find this Post
I'm not sure about if you mean this, but you can try the toString() method in currency format this way:
double number = 1.2;
string numberCurrency = number.ToString("C");
Console.WriteLine(numberCurrency); //this prints "1.20"
I recommend you to read this https://msdn.microsoft.com/es-es/library/kfsatb94(v=vs.110).aspx
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have two dates.
ReleaseDates = "11/2/2016";
LiveDate = "11/02/2016";
In the above two dates are same. But in my below coding it returns FALSE.
if (ReleaseDates.Contains(LiveDate.TrimStart(new Char[] { '0' })))
{
}
Your code does not work because TrimStart removes characters at the start of the string. It looks like LiveDate has no zeros at the beginning; the character '0' that you want to trim is at index 3, preceded by other characters. That is why it is not getting trimmed.
Comparing strings representing dates is an error-prone strategy. You would be better off parsing both strings, and comparing the results as DateTime objects.
In general, you should keep dates as objects designed for date representation - for example, DateTime or DateTimeOffset. This would let you customize date representation for display purposes, and avoid errors when date format changes from mm/dd to dd/mm.
This is because you are not comparing dates, you are comparing two strings that are not the same. Your best shot here is parsing first and then comparing.
DateTime releaseDate = DateTime.Parse(ReleaseDates);
DateTime liveDate = DateTime.Parse(LiveDate);
if (releaseDate == liveDate) // This should be true.
{
// Do stuff.
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I know that DateTime parsing can be tricky, but since there are a lot of mechanisms are relying on DateTime.Parse() especially its DateTime.Parse(string) overload, I think it makes sense to understand how does it work under the hood and how does it behave on different inputs.
What we know:
MSDN states when you use the DateTime.Parse(String) overload, the formatting is derived from the CurrentThread.Culture, however it draws the attention:
culture-specific data can change (and it did) between the different versions of the framework
the culture-specific data can be overridden by the OS settings
DateTime.Parse() tries to be smart
Because of these it's a bit hard for me to predict what will be result when somebody calls this function on different user inputs.
Even when I specify a culture, DateTime.Parse can recognize strings as valid DateTimes what you might not think to recognize. For example, all the following dates are valid - here are some of my findings:
var at = new System.Globalization.CultureInfo("de-AT", false);
System.Threading.Thread.CurrentThread.CurrentCulture = at;
// it doesn't care about the order:
DateTime.Parse("21.12.2020", at).Dump();
DateTime.Parse("2020.12.31", at).Dump();
// it accepts multiple separators:
DateTime.Parse("2020,12,31", at).Dump();
DateTime.Parse("2020/12/31", at).Dump();
DateTime.Parse("2020 12 31", at).Dump();
// it accepts multiple separators even in a single string:
DateTime.Parse("1999/12-31", at).Dump();
// year must consist at least 3 digits:
DateTime.Parse("100/12-31", at).Dump(); // this works
//DateTime.Parse("99/12-31", at).Dump(); -> this doesn't
DateTime.Parse("001/12-31", at).Dump(); // but this works again (3 digits)
// trimming (well, MSDN mentions this)
DateTime.Parse(" 100/12,31 ", at).Dump();
For me it's not so clear what's going on here. The separators / and , are not even mentioned in the DateTimeFormatInfo.CurrentInfo so I have no idea where did it come from. Are these separators hardcoded in DateTime.Parse? I tried to read the disassembled code, but it was a bit complex for me.
Is there any easy way to summarize what happens and which formats are supported?
I know that in a "real life example" if I have to parse a DateTime with a given format, I should use ParseExact instead, but since there are a lot of stuff relying on this (such as ASP.NET MVC model binding) I think it worths a question what it does exactly - and why does it recognize "100/3.14" as a valid DateTime instead of a division :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a problem that I'm not able to solve.
I'm getting a value from a Database. This value in the database is saved as a nvarchar.
I need to understand the type of the value.
For example:
12.12.2012 -> DateTime
15:00 -> Time
67.45 -> Double
For undesrtand the type I use the TryParse method.
Example for understand if it is a DateTime I execute this code:
DateTime valueConverted;
if(DateTime.TryParse(input.ToString(), out valueConverted))
{
// IS DATETIME
}
The problem is that if the value got from the DataBase is:
0900
009000
I would like the recognize it as a String. The problem is that the conversion to a double has success and then the value is converted to a double with value = 900.
How can I recognize that the value like 0900, 00060 are not double but String?
The simplest would probably be to match against ^0[0-9]+$.
Realize though this is a non-trivial problem and you're bound to find edge cases you didn't expect. I recommend changing the data model if you are at all able, and either store different types in different columns or have a separate column that denotes the data type stored. Storing everything as a string is generally a Bad Idea.
This seems massively oversimplified, but based on your description it will do the trick:
if (!string.IsNullOrEmpty(input) &&
input[0] == '0' &&
input.All(c => char.IsDigit(c)))
{
// We have a string.
}
you can used regex-match
create all type of datatype format string and match with regex.
http://www.dotnetperls.com/regex-match
if (input.StartsWith("0"))
{
// string
}
else
{
// double
var number = double.Parse(input);
}