Caverman
Caverman

Reputation: 3707

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.

Upvotes: 0

Views: 2707

Answers (2)

henoc salinas
henoc salinas

Reputation: 1054

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;
}

Upvotes: 1

Andrew Shepherd
Andrew Shepherd

Reputation: 45232

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

Upvotes: 1

Related Questions