Tuesday, March 1, 2011

Most efficient way to convert a string to 2 decimal places in C#

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

3000 => 30.00
 300 =>  3.00
  30 =>   .30
From stackoverflow
  • 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'
    
    Samuel : He said the input is a string, not an integer.
    Murtaza RC : works like a charm ! thanks a lot
    Murtaza RC : well I can convert it to an int :)
    Samuel : Then you really should say that.
    Murtaza RC : There - you have your answer ...convert the string to int :)
    Daniel Brückner : Parsing if not required and converting back is not smart ... ^^
  • Use tryParse to avoid exceptions.

    int val;
    
    if (int.Parse(input, out val)) {
        String.Format("{0,0:N2}", val / 100.0);
    }
    
    Samuel : You don't have to cast to double if one side is already double. It will cast to double automatically.
  • 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

0 comments:

Post a Comment