How to convert a string to decimal with 2 decimal places?

I’m trying to convert a string to a decimal but have the last two values be the decimal point. Example: “001150” be converted into 11.50.

Everything I’ve found in my search will convert strings to a decimal but the string already has the decimal point. I might have to create a function that will make the decimal point out of the string but wanted to see if there are any other ideas first.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

    string input = "001150";
    string convertedString = string.Format(
        "{0:N2}",
        double.Parse(input)/100.0
    );

Method 2

First check if string is a number, then divide by 100 and then format string:

public string ConvertTwoDecimals(string toConvert)
  {
    Double convertedValue;
    var isNumber = Double.TryParse(toConvert, out convertedValue);
    return isNumber ? $"{(convertedValue / 100):N2}" : $"{ 0:N2}";
  }

if you need a decimal type without formatted:

public decimal ConvertToDecimal(string toConvert)
{
  Decimal convertedValue;
  var isNumber = Decimal.TryParse(toConvert, out convertedValue);
  return isNumber ? convertedValue/100 : 0;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x