简体   繁体   中英

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

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'

Use tryParse to avoid exceptions.

int val;

if (int.Parse(input, out val)) {
    String.Format("{0,0:N2}", val / 100.0);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM