tags:

views:

2143

answers:

3

I have a string which needs a decimal place inserted to give a precision of 2.

3000 => 30.00
 300 =>  3.00
  30 =>   .30
+10  A: 

Given a string input, convert to integer, divide by 100.0 and use String.Format() to make it display two decimal places.

String.Format("{0,0:N2}", Int32.Parse(input) / 100.0)

Smarter and without converting back and forth - pad the string with zeros to at least two characters and then insert a point two characters from the right.

String paddedInput = input.PadLeft(2, '0')

padedInput.Insert(paddedInput.Length - 2, ".")

Pad to a length of three to get a leading zero. Pad to precision + 1 in the extension metheod to get a leading zero.

And as an extension method, just for kicks.

public static class StringExtension
{
  public static String InsertDecimal(this String @this, Int32 precision)
  {
    String padded = @this.PadLeft(precision, '0');
    return padded.Insert(padded.Length - precision, ".");
  }
}

// Usage
"3000".InsertDecimal(2);

Note: PadLeft() is correct.

PadLeft()   '3' => '03' => '.03'
PadRight()  '3' => '30' => '.30'
Daniel Brückner
He said the input is a string, not an integer.
Samuel
works like a charm ! thanks a lot
Murtaza RC
well I can convert it to an int :)
Murtaza RC
Then you really should say that.
Samuel
There - you have your answer ...convert the string to int :)
Murtaza RC
Parsing if not required and converting back is not smart ... ^^
Daniel Brückner
A: 

Use tryParse to avoid exceptions.

int val;

if (int.Parse(input, out val)) {
    String.Format("{0,0:N2}", val / 100.0);
}
Tarion
You don't have to cast to double if one side is already double. It will cast to double automatically.
Samuel
A: 

here's very easy way and work well.. urValue.Tostring("F2")

let say.. int/double/decimal urValue = 100; urValue.Tostring("F2"); result will be "100.00"

so F2 is how many decimal place u want if you want 4 place, then use F4