If I have numbers as a text string without decimal places, how can I convert it to 2 decimal places such that 12345 is converted to 123.45? The string can be any length greater than 1.
+1
A:
Convert it to your decimal type then divide by 100.
string stringVal = "12345";
decimal val = decimal.Parse( stringVal ) / 100M;
double val = double.Parse( stringVal ) / 100.0;
Convert it back to a string using
string newVal = string.Format( "{0:N}", val );
tvanfosson
2009-04-03 16:07:43
+1
A:
If you are convinced that it is numeric and don't want to double check, then you can avoid the conversions:
if (stringVal.Length == 2)
{
stringVal = "0." + stringVal;
}
else
{
stringVal = stringVal.Insert(x.Length - 2, ".");
}
This assumes you want a leading zero if it's 2 digits.
David M
2009-04-03 16:11:07
+1
A:
If you want the result as a string, you can just use string operations (examples in C#):
value.Substring(0, value.Length-2) + "." + value.Substring(value.Length-2)
If you want the result as a number, first parse the value then divide by 100:
double.Parse(value) / 100.0
Guffa
2009-04-03 16:13:10