C# 将字符串转换为小数点后两位

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

Convert string to 2 decimal place

c#

提问by william007

I have a string (confirm to be of decimal expression) 0.4351242134

我有一个字符串(确认是十进制表达式)0.4351242134

I want to convert to a string with two decimal place 0.44

我想转换为带有两位小数的字符串 0.44

How should I do in C#?

我应该如何在 C# 中做?

采纳答案by Ilya Ivanov

var probablyDecimalString = "0.4351242134";
decimal value;
if (Decimal.TryParse(probablyDecimalString , out value))
    Console.WriteLine ( value.ToString("0.##") );
else
    Console.WriteLine ("not a Decimal");

回答by Zak

float f = float.Parse("0.4351242134");
Console.WriteLine(string.Format("{0:0.00}", f));

See thisfor string.Format.

有关string.Format 的信息,请参阅此内容

回答by Mharlin

var d = decimal.Parse("0.4351242134");
Console.WriteLine(decimal.Round(d, 2));

回答by Renatas M.

Well I would do:

好吧,我会这样做:

var d = "0.4351242134";
Console.WriteLine(decimal.Parse(d).ToString("N2"));

回答by Rohit

Would this help

这有帮助吗

double ValBefore= 0.4351242134;
double ValAfter= Math.Round(ValBefore, 2, MidpointRounding.AwayFromZero); //Rounds"up"

回答by Enkode

float myNumber = float.Parse("0.4351242134");
Console.WriteLine(string.Format("{0:f2}", myNumber ));

https://msdn.microsoft.com/en-us/library/s8s7t687.aspx

https://msdn.microsoft.com/en-us/library/s8s7t687.aspx