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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/711264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 14:22:21  来源:igfitidea点击:

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

c#string

提问by Murtaza Mandvi

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

我有一个string需要插入小数位才能得到 2 的精度。

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

采纳答案by Daniel Brückner

Given a string input, convert to integer, divide by 100.0 and use String.Format() to make it display two decimal places.

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

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.

填充到长度为 3 以获得前导零。在扩展方法中填充到 precision + 1 以获得前导零。

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() 是正确的。

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

回答by Tarion

Use tryParse to avoid exceptions.

使用 tryParse 来避免异常。

int val;

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

回答by Tarion

here's very easy way and work well.. urValue.Tostring("F2")

这是非常简单的方法并且效果很好.. urValue.Tostring("F2")

let say.. int/double/decimal urValue = 100; urValue.Tostring("F2"); result will be "100.00"

比方说.. int/double/decimal urValue = 100; urValue.Tostring("F2"); 结果将是“100.00”

so F2 is how many decimal place u want if you want 4 place, then use F4

所以F2是你想要的小数位数,如果你想要4位,然后使用F4