Convert string to 2 decimal places

I have a line (confirm that it has a decimal expression) 0,4351242134

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

How do I do in C #?

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

Well, I would do:

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

See this for string.Format.

+2
source

It would help

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

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

0
source

Source: https://habr.com/ru/post/923474/


All Articles