繁体   English   中英

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

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

我有一个string ,需要插入小数位,以提供2的精度。

3000 => 30.00
 300 =>  3.00
  30 =>   .30

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

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

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

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

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

填充到三个长度以获得前导零。 在扩展方法中填充精度+ 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);

注意:PadLeft()是正确的。

PadLeft()   '3' => '03' => '.03'
PadRight()  '3' => '30' => '.30'

使用tryParse来避免异常。

int val;

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

这里非常简单,工作得很好.. urValue.Tostring(“F2”)

让我们说.. int / double / decimal urValue = 100; urValue.Tostring( “F2”); 结果将是“100.00”

所以如果你想要4个地方,F2是你想要的小数位数,那么使用F4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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