Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

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
like image 383
Murtaza Mandvi Avatar asked Dec 06 '22 06:12

Murtaza Mandvi


1 Answers

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'
like image 80
Daniel Brückner Avatar answered Jan 06 '23 09:01

Daniel Brückner