C# 如何仅显示最多 2 个小数位的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15288134/
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
How to display values only upto 2 decimal places
提问by Running Rabbit
I have a table column "Amount" of type money. When I am retrieving its value through a store procedure, it returns the value upto 4 decimal places(because of type money). I want the value upto two decimal places and I want it to handle in the code. How will I do it by rounding off the value to 2 decimal place. Thanks
我有一个钱类型的表格列“金额”。当我通过存储过程检索它的值时,它返回最多 4 个小数位的值(因为类型为货币)。我希望该值最多保留两位小数,并且我希望它在代码中处理。我将如何通过将值四舍五入到小数点后两位来做到这一点。谢谢
采纳答案by Running Rabbit
Well, I tried it and got the correct result.
嗯,我试了一下,得到了正确的结果。
Below is the code that I used:
下面是我使用的代码:
funding.amount= Math.Round(decimal.Parse(dr["Amount"].ToString()), 2).ToString();
//since the amount was of string type, therefore I used the above code. we can also use the below code:
//由于金额是字符串类型,所以我使用了上面的代码。我们也可以使用以下代码:
decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);
回答by Mitch Wheat
Format in presentation layer:
表示层格式:
string.Format("{0:#.##}", value);
回答by p.s.w.g
Read Custom Numeric Formatsfor detailed instructions on formatting numbers.
有关格式化数字的详细说明,请阅读自定义数字格式。
value.ToString("0.00");
In C# 6 or later, you can use string interpolationfor a somewhat cleaner syntax.
在 C# 6 或更高版本中,您可以使用字符串插值来获得更简洁的语法。
$"{value:0.00}";
回答by Gian Acuna
You can use Standard Numeric FormatExample:
您可以使用标准数字格式示例:
decimal dValue = 1.268;
string sValue = dValue.ToString("N"); // 1.27
回答by sree aneev
In Leave Event write this code
在离开事件中编写此代码
Double x;
Double.TryParse(txtLocl.Text, out x);
txtLocl.Text = x.ToString("0.00");
After leaving it allowed only two decimal places
离开后只允许两位小数
回答by Nitin Dhapte
string.Format("{0:0.00}", your_value);
回答by Meysam Ghorbani
test this code:
测试这段代码:
value.ToString("F2");