简体   繁体   中英

Convert string to 2 decimal place

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

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

How should I do in C#?

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

Well I would do:

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

See this for string.Format.

Would this help

double ValBefore= 0.4351242134;
double ValAfter= Math.Round(ValBefore, 2, MidpointRounding.AwayFromZero); //Rounds"up"
float myNumber = float.Parse("0.4351242134");
Console.WriteLine(string.Format("{0:f2}", myNumber ));

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

First, you must parse using a culture or you may loose the decimals. Next, you must have a text result to have a fixed count of decimals. Finally, you round to two decimals, but ToString() can do that for you, thus:

string amount5 = "2.509"; // should be parsed as 2.51

decimal decimalValue = Decimal.Parse(amount5, System.Globalization.CultureInfo.InvariantCulture);
string textValue = decimalValue.ToString("0.00");

// 2.51

Convert.ToDecimal(Value).ToString("N2")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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