C#中的四舍五入十进制值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/780570/
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-05 00:53:16  来源:igfitidea点击:

Round Off decimal values in C#

c#decimalnumbersrounding

提问by Guddu

how do i round off decimal values ?
Example :

我如何舍入十进制值?
例子 :

decimal Value = " 19500.98"

十进制值 =“19500.98”

i need to display this value to textbox with rounded off like " 19501 "

我需要将此值显示到文本框,四舍五入,如“19501”

if decimal value = " 19500.43"

如果十进制值 = " 19500.43"

then

然后

value = " 19500 "

值 = " 19500 "

采纳答案by Jon Skeet

Look at Math.Round(decimal)or the overload which takes a MidpointRoundingargument.

看看Math.Round(decimal)MidpointRounding参数的重载

Of course, you'll need to parse and format the value to get it from/to text. If this is input entered by the user, you should probably use decimal.TryParse, using the return value to determine whether or not the input was valid.

当然,您需要解析和格式化该值以从/到文本获取它。如果这是用户输入的输入,您可能应该使用decimal.TryParse,使用返回值来确定输入是否有效。

string text = "19500.55";
decimal value;
if (decimal.TryParse(text, out value))
{
    value = Math.Round(value);
    text = value.ToString();
    // Do something with the new text value
}
else
{
    // Tell the user their input is invalid
}

回答by Paul Alexander

Math.Round( value, 0 )

Math.Round( 值, 0 )

回答by NinethSense

d = decimal.Round(d);

回答by Manish Basantani

Try this...

尝试这个...

 var someValue=123123.234324243m;
 var strValue=someValue.ToString("#");

回答by Bilal

Total = Math.Ceiling(value)

Reply if it helps you

如果对你有帮助就回复

回答by Adedamola

string text = "19500.55";
text =(decimal.TryParse(text, out value))? (Math.Round(decimal.Parse(text))).ToString():"Invalid input";