Home > Back-end >  Convert a string to decimal with specific format
Convert a string to decimal with specific format

Time:10-26

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?

CodePudding user response:

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.

CodePudding user response:

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(" ", "");
  •  Tags:  
  • c#
  • Related