Reputation: 18525
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#?
Upvotes: 12
Views: 102162
Reputation: 398
If you need only one line of code;
decimal strdec = strvar != null ? decimal.Round(decimal.Parse(strvar), 2) : 0m;
Upvotes: 0
Reputation: 55816
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
Upvotes: 3
Reputation: 4783
float myNumber = float.Parse("0.4351242134");
Console.WriteLine(string.Format("{0:f2}", myNumber ));
https://msdn.microsoft.com/en-us/library/s8s7t687.aspx
Upvotes: 2
Reputation: 10236
Would this help
double ValBefore= 0.4351242134;
double ValAfter= Math.Round(ValBefore, 2, MidpointRounding.AwayFromZero); //Rounds"up"
Upvotes: 1
Reputation: 11820
Well I would do:
var d = "0.4351242134";
Console.WriteLine(decimal.Parse(d).ToString("N2"));
Upvotes: 10
Reputation: 23626
var probablyDecimalString = "0.4351242134";
decimal value;
if (Decimal.TryParse(probablyDecimalString , out value))
Console.WriteLine ( value.ToString("0.##") );
else
Console.WriteLine ("not a Decimal");
Upvotes: 15
Reputation: 1705
var d = decimal.Parse("0.4351242134");
Console.WriteLine(decimal.Round(d, 2));
Upvotes: 10