在C#中将字符串转换为2位小数的最有效方法

Mur*_*dvi 4 c# string

我有一个string需要插入小数位的精度为2.

3000 => 30.00
 300 =>  3.00
  30 =>   .30
Run Code Online (Sandbox Code Playgroud)

Dan*_*ner 15

给定一个字符串输入,转换为整数,除以100.0并使用String.Format()使其显示两个小数位.

String.Format("{0,0:N2}", Int32.Parse(input) / 100.0)
Run Code Online (Sandbox Code Playgroud)

更智能,无需来回转换 - 用零填充字符串至少两个字符,然后从右边插入两个字符.

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

padedInput.Insert(paddedInput.Length - 2, ".")
Run Code Online (Sandbox Code Playgroud)

填充到三个长度以获得前导零.在扩展方法中填充精度+ 1以获得前导零.

而作为一种扩展方法,只是为了踢.

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);
Run Code Online (Sandbox Code Playgroud)

注意:PadLeft()是正确的.

PadLeft()   '3' => '03' => '.03'
PadRight()  '3' => '30' => '.30'
Run Code Online (Sandbox Code Playgroud)