views:

142

answers:

6

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
+1  A: 

Just divide it by 100.0.

x = int(x)
x /= 100.0
vartec
+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
+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
A: 

decimal str=12345;
(str/100).ToString("F");

Kthevar
A: 

Thanks very much to all who replied. These are very helpful answers. They all solve my problem.